0
public class Node
{
Node next, child;
String data;
Node()
{
this(null);
}
Node(String s)
{
data = s;
next = child = null;
}
Node get(int n)
{
Node x = this;
for(int i=0; i<n; i++)
x = x.next;
return x;
}
int length()
{
int l;
Node x = this;
for(l=0; x!=null; l++)
x = x.next;
return l;
}
void concat(Node b)
{
Node a = this.get(this.length() - 1);
a.next = b;
}
void traverse()
{
Node x = this;
while(x!=null)
{
System.out.println(x.data);
x = x.next;
}
}
}
class IntegerNode extends Node
{
int data;
IntegerNode(int x)
{
super();
data = x;
}
}
有什麼辦法,我可以有不同類型的data
兩個類,這樣我就可以使用IntegerNode
類號和Node
類的字符串?不同類型的數據在不同的班級
例子:
public class Test
{
public static void main(String args[])
{
IntegerNode x = new IntegerNode(9);
IntegerNode y = new IntegerNode(10);
x.concat(y);
x.concat(new Node("End"));
x.traverse();
}
}
現在,這是我得到的輸出: null
null
End
任何解釋會有所幫助。先謝謝你。
我同意這是一個更好的方法,但不會讓用戶選擇超出整數和字符串的數據類型嗎? – Nerzid
是的確如此,但您可以提供整數和字符串的具體實現,如果這些是您想要使用的唯一2個。順便說一下,* generics *的專有名稱是'參數化類型'。 – vikingsteve
謝謝。泛型是我在找的 – RJacob41