所以我有這個鏈表類:重新使用鏈接的另一種類型的列表(泛型類型)
public class LinkedList {
private LLNode rootNode;
public Node FindItemByData(String data) {
if(rootNode == null)
return null;
else
return rootNode.findItemByData(data);
}
而這個節點類:
public class LLNode {
LLNode tail; //tail node
Node data; //some data
public LLNode(LLNode tail, Node data)
{
this.tail = tail;
this.data = data;
}
public Node findItemByData(String data) {
if(this.data.name.equals(data))
return this.data;
else
return this.tail.findItemByData(data);
}
我想重新使用鏈接列表用於在LLNode的每個Node data
內的圖形中存儲邊緣。我使用Generic Types取代了類型,但是這破壞了findItemByData
函數的功能,因爲它依賴於顯式聲明爲Node的數據。
有什麼辦法可以重用這個類的多種類型?或者我不應該在泛型類中提到data.name
?
執行方面:
public class Graph {
//USE LINKED LIST
LinkedList Nodes;
//Node[] Nodes;
int noOfNodes;
public Graph() {
noOfNodes = 0;
//Nodes = new Node[25];
Nodes = new LinkedList();
}
public void AddNode(String name, int x, int y) {
//Nodes[noOfNodes++] = new Node(name,x,y);
Nodes.AddItem(new Node(name,x,y));
}
..
public class Node {
String name; //Node's name
int x,y; //Node's coords
LinkedList Adjacencies;
int noOfAdj = 0;
int size = 0;
public Node(String name, int x, int y) { //Constructor
this.name = name;
this.x = x;
this.y = y;
Adjacencies = new LinkedList();
}
public void addAdjacency(String dest, double distance) {
Adjacencies.AddItem(new Edge(this.name, dest, distance)); //I want to do this
}
}
編輯:嘗試在使用泛型:
public class LinkedList<T> {
private LLNode rootNode;
public T FindItemByData(String data) {
if(rootNode == null)
return null;
else
return rootNode.findItemByData(data);
}
}
public class LLNode<T> {
LLNode tail; //tail node
T data; //some data
public LLNode(LLNode tail, T data)
{
this.tail = tail;
this.data = data;
}
public T findItemByData(String data) {
if(this.data.name.equals(data))
return (T) this.data;
else
return (T) this.tail.findItemByData(data);
}
}
public class Graph {
LinkedList<Node> Nodes;
int noOfNodes;
public Graph() {
noOfNodes = 0;
Nodes = new LinkedList();
}
public void AddNode(String name, int x, int y) {
Nodes.AddItem(new Node(name,x,y));
}
}
public class Node {
String name; //Node's name
int x,y; //Node's coords
LinkedList<Edge> Adjacencies;
int noOfAdj = 0;
int size = 0;
public Node(String name, int x, int y) { //Constructor
this.name = name;
this.x = x;
this.y = y;
Adjacencies = new LinkedList();
}
public void addAdjacency(String dest, double distance) {
Adjacencies.AddItem(new Edge(this.name, dest, distance)); //I want to do this
}
}
爲了闡明,節點鏈表要存儲Node類型的對象,其中作爲鄰接鏈表需要是Edge類型。 – bene96
嘿埃裏克,顯示的代碼是在我嘗試泛型之前。我嘗試過'公共類LLNode {..}'並將數據聲明爲'T data',但這不起作用,因爲LLNode的方法依賴於節點類型('findItemByData') –
bene96