简体   繁体   中英

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?

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

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. 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. As my solution fully "separates" a Node<Integer> form a Node<String> . And yes, that means that users could create Node<Whatever> objects at any time.

Thus: if you really want only Integer and String data nodes - then you would actually do the following:

  • make the base Node class hold data as Object
  • make the base class abstract
  • create two specific subclasses for Integer/String, as outlined in the other answer

But the question would be: what happens when you decide next week that you want Float and Double, too. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM