不同类别中的不同类型的数据

时间:2017-08-28 05:48:12

标签: java inheritance data-structures types

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 个答案:

答案 0 :(得分:1)

默认方式是使用 generics

像:

public class Node <T> {
  private final T data;

  public Node(T data) { this.data = data; }

然后使用like:

Node<Integer> intNode = new Node<>(5);
Node<String> stringNode = new Node<>("five");

请注意:上面的 是您在Java中解决此类问题的方法。在这里使用继承将是一个相当错误的方法。除非你真的找到一个很好的理由,能够通过不同的数据concat()节点。由于我的解决方案完全“分离”Node<Integer>形式Node<String>。是的,这意味着用户可以随时创建Node<Whatever>个对象。

因此:如果您真的想要整数和字符串数据节点 - 那么您实际上会执行以下操作:

  • 使基本Node类保存数据为Object
  • 使基类抽象
  • 为Integer / String创建两个特定的子类,如另一个答案中所述

但问题是:当你下周决定你想要Float和Double时会发生什么。也许日期?然后,您每次都必须创建新的子类。导致大量重复的代码。

所以真正的回答:真的认为通过你的要求。了解您想要构建的内容。然后看看你应该走哪条路。

相关问题