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