尽管在LinkedList的Node类中实现了toString方法,但仍然获得了奇怪的输出

时间:2013-04-27 04:35:21

标签: java data-structures linked-list

请考虑以下链接列表代码。基本上我已经在LinkedList类中创建了tthree节点并尝试显示内容,但我是 得到奇怪的输出despit在“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();



}

}

如果我错了,请纠正我。

谢谢

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

Object.toString()的默认实现是

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

这意味着,你的班级名称加上你班级哈希码的@ + + hexa表示。

由于您的类Node 未覆盖 toString(),因此Object.toString()将被调用(因为Object是所有类的父类)和{{ 1}}将被打印。

在你的Node类中覆盖MyPackage.Node@1d450337,如下所示

toString()

答案 2 :(得分:-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.