[英]Different types of data in different classes
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
任何解释都会有所帮助。 先感谢您。
默认方式是使用泛型 。
喜欢:
public class Node <T> {
private final T data;
public Node(T data) { this.data = data; }
然后使用像:
Node<Integer> intNode = new Node<>(5);
Node<String> stringNode = new Node<>("five");
请注意: 以上是解决Java中此类问题的方法。 在这里使用继承将是一个相当错误的方法。 除非您真的找到一个很好的理由能够将不同数据的concat()
节点连接起来。 当我的解决方案完全“分离” Node<Integer>
形成Node<String>
。 是的,这意味着用户可以随时创建Node<Whatever>
对象。
因此:如果您只需要 Integer和String数据节点,那么您实际上将执行以下操作:
Object
但是问题是:当您下周决定也要Float和Double时会发生什么。 也许日期? 然后,您每次都必须创建新的子类。 导致很多重复的代码。
因此,这里的真正答案是:认真考虑您的要求。 了解您到底要构建什么。 然后查看您应该走哪条路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.