0

请考虑链接列表的以下代码。基本上,我在 LinkedList 类中创建了三个节点并尝试显示内容,但我得到了奇怪的输出,尽管在“Node”类中实现了“toString()”方法。谁能告诉我有什么问题?

我得到的输出如下: 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();



}

}

如果我在某个地方错了,请纠正我。

谢谢

4

3 回答 3

1

您看到的输出是通用java.lang.Object.toString()输出。您粘贴的代码不包含任何名为toString().

如果您的意图是这样data()getData()将被视为toString(),您必须明确地这样做。

于 2013-04-27T04:47:01.663 回答
0

的默认实现Object.toString()

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

这意味着,你的类名 + @ + 你类的哈希码的十六进制表示。

由于您的类 Node没有覆盖,将被调用(因为它是所有类的父类)并将被打印。toString()Object.toString()ObjectMyPackage.Node@1d450337

像这样覆盖toString()你的 Node 类

class Node {

 ....


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


}
于 2013-04-27T04:52:24.487 回答
-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.
于 2013-04-27T05:06:27.747 回答