0

Please consider the following code for linkedlist. Basically I've created tthree nodes in the LinkedList class and trying to display the contents but I'm getting weird output despit implementing "toString()" method inside "Node" class. Could anyone tell me what's the problem ?

The output I'm getting is as follows: MyPackage.Node@1d450337

package MyPackage;


class Node {

String data;
Node next;

public Node(String data, Node next){

    this.data = data;
    this.next = next;

}

public String getData(){
    return data;
}

public Node getNext(){

    return next;
}

public void setNext(String data){
    this.data = data;
}

 public String data() {
     return data;
 }


}

// CREATING LINKED LIST BACKWARDS AND APPLYING SOME OPERATIONS ON IT


class LinkedList{

Node cNode = new Node("C", null);

Node bNode = new Node("B", cNode);

Node list = new Node("A", bNode);


public void DisplayLinkedList(){

    System.out.println(list);

}



}




public class LinkedListByME {


public static void main(String[] args) {


    LinkedList ll = new LinkedList();
    ll.DisplayLinkedList();



}

}

Please correct me if I'm wrong somewhere.

Thanks

Dennis Meng
  • 5,109
  • 14
  • 33
  • 36
Tan
  • 1,433
  • 5
  • 27
  • 47
  • Rolled it back since editing the fix into the question would invalidate the answers (code in a question about a problem is also no good if the code doesn't repro the problem anymore) – Dennis Meng Oct 10 '14 at 06:59

3 Answers3

1

The output you're seeing is the generic java.lang.Object.toString() output. The code you have pasted doesn't contain any methods named toString().

If your intention is that data() or getData() will be treated as a toString(), you'll have to do so explicitly.

Sastrija
  • 3,284
  • 6
  • 47
  • 64
Matt Rick
  • 146
  • 1
  • 6
  • Thanks for your reply, I got it corrected by adding explicitly, public String toString(){ return this.data; } – Tan Apr 27 '13 at 04:49
0

the default implementation of Object.toString() is

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

This means, concantination of your class name + @ + hexa representation of hashcode of your class.

Since your class Node has not overriden the toString(), Object.toString() will be called (since Object is the parent class for all class) and MyPackage.Node@1d450337 will be printed.

override toString() in your Node class like this

class Node {

 ....


 @Override
 public String toString() {
     return data;
 }


}
sanbhat
  • 17,522
  • 6
  • 48
  • 64
-1
The output you are getting is correct.Actually in DisplayLinkedList Method you have printed the address of the node that contains your string and thats why its printing Node@1d450337.

If you add the following line in your DisplayLinkedList Method you will get the desired output.

public void DisplayLinkedList(){

    System.out.println(list.data);

}

Hope this is what is your requirement.