2016-01-31 62 views
1
public class IntList { 
    private IntNode _head; 
    public IntList() { 
     _head = null; 
    } 
} 

我創建了一個名爲IntList的類。 IntList包含一個搜索具有指定int值的IntNode對象的方法。這是方法:將一個變量分配給另一個變量後,爲什麼更改一個變量不會改變另一個?

public boolean findElementInList(int value) { 
    IntNode currentNode = this._head; 

    while (currentNode.getValue() != value && 
      currentNode.getNext() != null) { 
     currentNode = currentNode.getNext(); 
    } 

    return (currentNode.getValue() == value); 
} 

的方法完成後,原_head實例變量是完整的 - 但爲什麼呢? currentNode指向方法中的_head(混疊),並且對currentNode所做的每個更改也應反映在_head(每次運行currentNode = currentNode.getNext();時)。

這是getNext()代碼:

public IntNode getNext() {return _next;} 
+1

currentNode是頭的另一個引用,並且您通過調用_head.getNext()將該引用更改爲列表中的下一個元素,除非getNext()以某種方式修改頭,否則頭不會更改 – SomeDude

+0

getNext() '回來?請包括'IntNode'的代碼。 – activedecay

回答

0

您在開始處將頭部的值分配給currentNode。把它看作是2個不同的指針指向內存中的相同值。但是,您繼續將列表中的下一個值分配給currentNode,而_head保持不變。順便說一句,如果你改變你的頭值,你將失去你的名單的頭。

+0

謝謝!的確,在開始時我指向'_head',但是currentNode指向'currentNode.getNext()' – Yos

0

你永遠不改變原有_head。你只是實例化currentNode,它指向_head。如果你想改變_head你應該在最後改變你的頭不同的價值,而不是指向它。例如_head = ...

0

您的head實例變量保持不變,因爲您不修改findElementInList方法中的任何內容。

舉個例子:

喜歡的東西

_head.setValue(10); 

currentNode = this._head; 
currentNode.setValue(10); 

會修改你的頭節點。在currentNode.setValue(10);的情況下,`this._head'的內容將因「別名」而被修改 - 兩個變量都指向相同的位置。

重要說明:爲currentNode分配新值根本不會修改this.head的值。它只讓currentNode指向一個新節點。因此,

currentNode = currentNode.getNext(); 

讓currentNode指向其後處理程序而不更改this._head的內容。這就是「指向對象的Java變量只是引用」的含義。

存在這樣的情況,其中,分配給一個變量將改變變量值:

currentNode.setValue(10);

int x = 10; x = x + 1; // x == 11

會突變一些值。在第一種情況下,您將更改第二種情況下的對象內容,您使用的是不是對某種對象的引用的所謂「原始值」。

相關問題