爲什麼發生這種情況?爲什麼打印輸出不爲空?
List<String> list = new ArrayList<String>();
list.add("aaa");
String s = list.get(0);
list.remove(0);
System.out.println(s);
控制檯說:aaa
有人可以解釋一下嗎?我以爲控制檯應該是null
,應該是?
爲什麼發生這種情況?爲什麼打印輸出不爲空?
List<String> list = new ArrayList<String>();
list.add("aaa");
String s = list.get(0);
list.remove(0);
System.out.println(s);
控制檯說:aaa
有人可以解釋一下嗎?我以爲控制檯應該是null
,應該是?
不,它按預期工作。 S
仍然保留對"aaa"
的引用。您只更改了列表,而不是S
。
'S'仍然保留對「aaa」實例的引用 – 2013-05-06 09:20:52
String s = list.get(0);
保存的參照s
,然後印刷它的價值。有什麼問題?
List#remove更改列表,而不是變量s
, s
仍然有參考"aaa"
。
你可能想切換順序:
list.remove(0);
String s = list.get(0);
沒有,因爲你存儲在一個s
從列表中選擇值。因此,對"aaa"
的引用在列表和s
中,在您從列表中刪除後,s
仍然引用它。
感謝你們所有人,我認爲obj shound被從內存中刪除,當操作list.remove(0)是完成。 – kevin 2013-05-06 10:16:22
讓我將它放入一個故事:
你自己寫的一張紙條上寫着「AAA」(只寫"aaa"
actualy定義了一個新的字符串),以確保您永遠不會忘記這一點。同時,您決定將另一張紙條釘在冰箱上告訴您先前放置紙幣的位置(list.add(...)
)可能是個好主意。
在某些情況下,您在冰箱上看到此信息並決定追蹤您的筆記(list.get(0)
)。然後你意識到你不再需要提醒了,因爲你手中拿着紙條,所以你從冰箱裏取出紙條(list.remove(0)
)。你還握着什麼?
我想這將是更加清晰,當你寫出來的代碼究竟發生了什麼,沒有任何ommitting步驟:
String note = "aaa";
List<String> fridge = new ArrayList<String>();
fridge.add(note);
note = null; // forget about the note, the fridge will remember
String someNote = list.get(0);
fridge.remove(0); // now the fridge forgets, but you still have the note
System.out.println(someNote);
非常感謝 – kevin 2013-05-06 10:17:11
當然它不應該。在將其從列表中刪除之前,您已將「aaa」分配給了's'。所以很自然,它仍然存在...... – 2013-05-06 09:17:40
應該有另一個關閉原因。太尷尬了。 :-) – 2013-05-06 09:18:58
我建議你在調試器中逐步執行代碼,並且你將能夠看到每行代碼的功能。 – 2013-05-06 09:24:15