[英]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;
}
}
Is there any way I can have different types of data
in the two classes so that I can use the IntegerNode
class with numbers and the Node
class with Strings? 有什么办法可以在两个类中使用不同类型的data
,以便可以将IntegerNode
类与数字一起使用,将Node
类与字符串一起使用?
Example: 例:
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();
}
}
Right now, this is the output I'm getting: null
null
End
现在,这是我得到的输出: null
null
End
Any explanation would help. 任何解释都会有所帮助。 Thank you in advance. 先感谢您。
The default way would be to use generics . 默认方式是使用泛型 。
Like: 喜欢:
public class Node <T> {
private final T data;
public Node(T data) { this.data = data; }
to then use like: 然后使用像:
Node<Integer> intNode = new Node<>(5);
Node<String> stringNode = new Node<>("five");
Please note: the above is how you solve such problems in Java. 请注意: 以上是解决Java中此类问题的方法。 Using inheritance here would a rather wrong approach. 在这里使用继承将是一个相当错误的方法。 Unless you would really find a good reason to be able to concat()
nodes with different data. 除非您真的找到一个很好的理由能够将不同数据的concat()
节点连接起来。 As my solution fully "separates" a Node<Integer>
form a Node<String>
. 当我的解决方案完全“分离” Node<Integer>
形成Node<String>
。 And yes, that means that users could create Node<Whatever>
objects at any time. 是的,这意味着用户可以随时创建Node<Whatever>
对象。
Thus: if you really want only Integer and String data nodes - then you would actually do the following: 因此:如果您只需要 Integer和String数据节点,那么您实际上将执行以下操作:
Object
使基本Node类将数据保存为Object
But the question would be: what happens when you decide next week that you want Float and Double, too. 但是问题是:当您下周决定也要Float和Double时会发生什么。 And maybe Dates? 也许日期? Then you would have to create new subclasses each time. 然后,您每次都必须创建新的子类。 Leading to a lot of duplicated code. 导致很多重复的代码。
So the real answer here: really think your requirements through. 因此,这里的真正答案是:认真考虑您的要求。 Understand what is exactly that you want to build. 了解您到底要构建什么。 And then see which path you should take. 然后查看您应该走哪条路。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.