2013-03-25 21 views
1

我有一個包含類型爲AClass的屬性的類(名爲AClass)。我試圖用這個來創建一個整數的鏈表。但是,只要我給AClass中的數據賦值,它就會用這個值替換所有鏈接類中的數據。不能使用「this」引用一個對象來創建一個鏈表

public class AClass { 
    public AClass rest; 
    public int data; 

    public AClass (int tData) { 
     data=tData; 
     rest=null; 
    } 

    public void add(int item) { 
     rest=this;   //This is what is causing the problem 
     data=item; 
    } 

}

這是我使用測試的內容。我的輸出應該是5,6,5,但我得到5,6,6。

public class Test { 
    public static void main(String[] args) { 
     AClass aTest=new AClass(5);  //Creates a list with on element. 
     System.out.println(aTest.data); //Print that element for verification 
     aTest.add(6); 
     System.out.println(aTest.data);  //Print the end element 
     System.out.println(aTest.rest.data); //Print the next element, which should be 5 
    } 
} 

我似乎無法弄清楚我做錯了什麼。

回答

3

讓我們考慮一下鏈表是什麼以及代碼的作用。

鏈表是由一系列指針鏈接在一起的一組節點。根據你所描述的預期行爲,你想要一個像這樣構建的鏈表。

public class Test { 
    public static void main(String[] args) { 
     AClass aTest=new AClass(5);   // Data: aTest ==> (5) ==> null 
     System.out.println(aTest.data);  // Prints 5. 
     aTest.add(6);      // Data: aTest ==> (6) ==> (5) ==> null 
     System.out.println(aTest.data);  // Prints 6 
     System.out.println(aTest.rest.data); // Prints 5 
    } 
} 

然而,鑑於你實現,你從來沒有真正創建第二個節點 - 你永遠只能有原來的節點,而你破壞你的鏈接列表。

public class Test { 
    public static void main(String[] args) { 
     AClass aTest=new AClass(5);   // Data: aTest ==> (5) ==> null 
     System.out.println(aTest.data);  // Prints 5. 
     aTest.add(6);      // Data: aTest ==> (6) ==> (6) ==> (6) ==> forever 
     System.out.println(aTest.data);  // Prints 6 
     System.out.println(aTest.rest.data); // Prints 6 
    } 
} 

所以你需要add創建一個新的節點:

rest=this;則將下一個指向當前對象,創建一個元素的循環鏈表。你需要創建一個新的元素。您還有一個有趣的問題,就是您認爲您要添加項目的方向是什麼。您可以添加到列表的前面或列表的後面,但請注意,添加到前面意味着將指針改變到前面。你可以很容易地同時實現addFrontaddBack

public AClass addFront(int item) { 
    AClass node = new AClass(item); 
    node.rest = this; 
    return node; 
} 

public void addBack(int item) { 
    // Find the end of the list 
    AClass temp = this; 
    while (temp.rest != null) { 
     temp = temp.rest; 
    } 
    temp.rest = new AClass(item); 
} 

之所以這麼說,可考慮使用內置的鏈接列表:http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html

2
public class AClass { 
    public AClass rest; 
    public int data; 

    public AClass (int tData) { 
     data=tData; 
    } 

    /** 
    * Insert in front. 
    * @param item data to be inserted. 
    */ 
    public void add(int item) { 
     // Make a copy of this: 
     AClass copy = new AClass(data); 
     copy.rest = rest; 
     // Overwrite this object: 
     rest = copy; 
     data = item; 
    } 
} 
0

aTest.rest.data

您正在使用的參考變量ATEST訪問實例變量休息型ACLASS的。 其餘a測試保持相同的參考。當你說aTest.rest.data跟它aTest.data數據的當前值的另一種方式。這就是爲什麼你得到5,6,6作爲輸出。

相關問題