I would really appreciate if you can help to answer to this question:
I have already created a custom linked list myself in a very standard way using Java. Below are
Your getData() in Node class returns an Object type. You need to cast it into a String so that it gets printed by println() properly.
System.out.println((String)tmp.getData());
should do the trick for you.
You need to override the toString()
method on Node
:
@Override
String toString() {
String val = // however you want to represent your Node
return val;
}
and print the node:
System.out.println(tmp);
Alternatively, have Node.getData()
return a String
if you know you are only going to store String
s -- change the Object
s to String
in the Node
definition
Alternatively, you could use generics to specify the type of data inside the node
UPDATE: after a little more thought (provoked by comments), I see something amiss:
tmp.getData()
should return a string (based on Node's single parameter ctor and that you are passing strings), but the output is about references to Node
objects. Is it possible that linkedList.add
re-sets the Node
's obj member to a Node
instead?
The LinkedList is of Objects, Objects toString method prints out the reference. If you want to print out the string you are going to have either change the LinkedList to a String/Generics or cast the print out like this:
String output = (String)tmp.getData();
System.out.println(output);
(you can do this in one line if you want).
Your linkedList
class already creates the Node
s for you!
linkedList list = new linkedList();
list.add("foo");
list.add("bar");
Node tmp = lst.getHead();
while(tmp != null){
System.out.println(tmp.getData());
tmp = tmp.getNext();
}
Will print
foo
bar