看板 java 關於我們 聯絡資訊
※ 引述《newjoy (職業格鬥家)》之銘言: : public class test { : private int index = 0; : public test() : { : this.index = 0; : } : public void setIndex(int index) : { : this.index = index; : } : public int getIndex() : { : return this.index; : } : public static void assignT(test t) : { : t = new test(); : } : public static void main(String[] args){ : test t1 = new test(); : t1.setIndex(9); : assignT(t1); : System.out.println("value : "+t1.getIndex()); : } : } : 如果傳入function 裡面的是 object的 reference, : 那為什麼執行assignT之後 : 印出來的值一樣是9而不是0?? : 假設 t1 的位址是 0xAA : 那傳進 assignT 裡的 t 會是copy的一份 0xAA的 object 位址 : 然後 t = new test(); 會把0xAA的內容指向一個新的 test實體, : 這樣理解有錯嗎? ------------------------------------------------------------------------------ after "assignT(t1);" before "t = new Test();" ┌─────┐0x00f00000 in stack memory0x10f10000│t1 @ main └┼────┘ └─────┐┌───────────┐ ↓↓ │ ┌─────┐0x10f10000 in heap memory │ │..........│an instance of class test │ └─────┘which is created @ main │ ┌──────────────────┘ ┌┼────┐0x00f20000 in stack memory0x10f10000│t @ assignT [when main call assignT] └─────┘the value is passed by main ------------------------------------------------------------------------------ after "t = new Test();" ┌─────┐0x00f00000 in stack memory0x10f10000│t1 @ main └┼────┘ └─────┐ ↓ ┌─────┐0x10f10000 in heap memory │..........│an instance of class test └─────┘which is created @ main ┌─────┐0x00f20000 in stack memory0x10f30000│t @ assignT [after "t = new Test();"] └┼────┘the value is assigned └─────┐ ↓ ┌─────┐0x10f30000 in heap memory │..........│an instance of class test └─────┘which is created @ assignT ------------------------------------------------------------------------------ back to main ┌─────┐0x00f00000 in stack memory0x10f10000│t1 @ main └┼────┘ └─────┐ ↓ ┌─────┐0x10f10000 in heap memory │..........│an instance of class test └─────┘which is created @ main ┌─────┐0x10f30000 in heap memory │..........│an instance of class test └─────┘which is created @ assignT It becomes a garbage. The reason is nobody can access this instance. ------------------------------------------------------------------------------ 如果我沒有理解錯的話, 除了, main 自己以外, 沒有其它的 method 可以改變 t1 @ main 的值。 -- ""是"喜歡"的累積! "喜歡"是"感覺"的累積! "感覺"是"緣份"的累積! "緣份"是"前世"的累積! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.104.29.8
Apohades:這圖案好精美 11/05 14:21
wendly777:簡單的說就是要把reference與instance搞清楚 11/05 21:49
wendly777:即使改成reference,不懂指標的人還是不懂reference 11/05 21:52