2013-05-06 219 views
-2

爲什麼發生這種情況?爲什麼打印輸出不爲空?

List<String> list = new ArrayList<String>(); 
list.add("aaa"); 
String s = list.get(0); 
list.remove(0); 
System.out.println(s); 

控制檯說:aaa

有人可以解釋一下嗎?我以爲控制檯應該是null,應該是?

+1

當然它不應該。在將其從列表中刪除之前,您已將「aaa」分配給了's'。所以很自然,它仍然存在...... – 2013-05-06 09:17:40

+1

應該有另一個關閉原因。太尷尬了。 :-) – 2013-05-06 09:18:58

+0

我建議你在調試器中逐步執行代碼,並且你將能夠看到每行代碼的功能。 – 2013-05-06 09:24:15

回答

1

不,它按預期工作。 S仍然保留對"aaa"的引用。您只更改了列表,而不是S

+0

'S'仍然保留對「aaa」實例的引用 – 2013-05-06 09:20:52

1

String s = list.get(0);

保存的參照s,然後印刷它的價值。有什麼問題?

List#remove更改列表,而不是變量s, s仍然有參考"aaa"

你可能想切換順序:

list.remove(0); 
String s = list.get(0); 
+0

你的回答是正確的,但是在'THIS'情況下切換順序會拋出'java.lang.IndexOutOfBoundsException'! – SudoRahul 2013-05-06 09:25:49

+0

是的,我知道,我正在重申一個情況,其中至少有兩個元素 – Maroun 2013-05-06 09:33:48

+0

你很親切 – kevin 2013-05-06 10:20:45

5

沒有,因爲你存儲在一個s從列表中選擇值。因此,對"aaa"的引用在列表和s中,在您從列表中刪除後,s仍然引用它。

+0

感謝你們所有人,我認爲obj shound被從內存中刪除,當操作list.remove(0)是完成。 – kevin 2013-05-06 10:16:22

1

讓我將它放入一個故事:

你自己寫的一張紙條上寫着「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); 
+0

非常感謝 – kevin 2013-05-06 10:17:11