2013-04-27 48 views
0

請考慮以下代碼中的鏈接列表。基本上我已經在LinkedList類中創建了三個節點,並嘗試顯示內容,但是我在 上得到了奇怪的輸出despit,它在「Node」類中實現了「toString()」方法。誰能告訴我有什麼問題?儘管在LinkedList的Node類中實現了toString方法,但獲得了奇怪的輸出結果

我得到的輸出如下: [email protected]

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(); 



} 

} 

請糾正我,如果我錯了地方。

感謝

+0

因爲編輯修復成問題將在一個問題的問題無效的答案(代碼軋製回來也沒有好,如果代碼不再重現問題) – 2014-10-10 06:59:54

回答

1

你看到的輸出是通用java.lang.Object.toString()輸出。您粘貼的代碼不包含任何名爲toString()的方法。

如果您的意圖是data()getData()將被視爲toString(),您必須明確地這樣做。

+0

感謝您的回覆,我通過明確添加更正了它, public String toString(){ return this.data; } – Tan 2013-04-27 04:49:32

0

Object.toString()的默認實現

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

這意味着,你的類名類的散列碼的+ @ +六表示concantination。

由於類節點有未覆蓋toString()Object.toString()將被調用(因爲Object是父類的所有類)和[email protected]將被打印。

覆蓋toString()在Node類這樣

class Node { 

.... 


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


} 
+0

非常感謝! – Tan 2013-04-27 04:53:41

-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 [email protected] 

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. 
相關問題