-4

Hi, I am trying create a linked list to store some data. How can I retrieve the actual data from the list values and not the item's object reference.

public class myList()
{
    private LinkedList<Node> list = null;

    public myList()
    {
        list = new LinkedList<Node>();
    }

    public void addX(Node x)
    {
       list.add(x)
    }

    public void print()
    {
        for(int i = 0; i<list.size(); i++)
        {
            System.out.println(list.get(i));
        }

     }
}

public class Node
{
    private String x;
    private int y;
    private int z;

    public Node(String x, int y, int z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}

public static void main (String[] args)
{
    myList.addX(new Node(x,1,2));
    myList.print();
}

When I run this it prints the memory address/reference instead of the actual values. What am I doing wrong? Example output: Node@838378c7

Any help is appreciated.

Thanks.

RobF
  • 2,758
  • 1
  • 20
  • 25
user2993831
  • 23
  • 3
  • 9

4 Answers4

3

toString() method in Object is

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

which is exactly what will get printed. You need to override it in Node class to show your output of toString().

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

The output you see is generated by the default toString()-method, to get an output format of your choice you need to override the toString()-method.

For more information see this question

Community
  • 1
  • 1
LionC
  • 3,106
  • 1
  • 22
  • 31
0

You are printing the Node class object which does not have a toString() method, and so it uses the the toString() of the Object class which prints the output that you see.

Override to toString() method and print the content in the the way you want in that method so that the output when when printing a Node object is as you expect it to be

anirudh
  • 4,116
  • 2
  • 20
  • 35
0

Override the toString method on the Node class:

public class Node
{
    private String x;
    private int y;
    private int z;

    public Node(String x, int y, int z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    @Override
    public String toString() {
        return x + "/" + y + "/" + z;
    }
}

This example returns the x, y and z values with a "/" seperator between each. However, you can obviously change the return value of the toString method to suit how you would like your data displayed.

This tutorial explains the concept quite well.

RobF
  • 2,758
  • 1
  • 20
  • 25