[英]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.