2017-08-28 34 views
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

任何解释会有所帮助。先谢谢你。

回答

1

默认方式是使用generics

像:

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>对象。

这样:如果你真的想整数和字符串数据节点 - 那么你实际上做到以下几点:

  • 制造基地Node类保持数据为Object
  • 使基类的抽象
  • 创建整数/字符串两个具体子类,如其他答案

但阙概述stion会是:当你下周决定你想要Float和Double时会发生什么。也许日期?然后你必须每次创建新的子类。导致许多重复的代码。

所以这里的真正回答:真的认为您的要求通过。了解你想要建立的是什么。然后看看你应该走哪条路。

+0

我同意这是一个更好的方法,但不会让用户选择超出整数和字符串的数据类型吗? – Nerzid

+0

是的确如此,但您可以提供整数和字符串的具体实现,如果这些是您想要使用的唯一2个。顺便说一下,* generics *的专有名称是'参数化类型'。 – vikingsteve

+1

谢谢。泛型是我在找的 – RJacob41