为什么会这样?
List<String> list = new ArrayList<String>();
list.add("aaa");
String s = list.get(0);
list.remove(0);
System.out.println(s);
控制台说:aaa
有人可以为我解释一下吗?我认为控制台应该是null
,应该是吗?
不,因为您将 list 中的值存储在s
. 因此,对 的引用"aaa"
既在列表中s
,又在从列表中删除后,s
仍然引用它。
不,它按预期工作。S
仍然持有对"aaa"
. 您只更改了列表,而不是S
.
String s = list.get(0);
您保存了对 的引用s
,然后打印了它的值。有什么问题?
List#remove更改列表,而不是变量s
,s
仍然引用"aaa"
.
您可能想要切换顺序:
list.remove(0);
String s = list.get(0);
让我把它变成一个故事:
你给自己写了一个“aaa”的注释(只是写"aaa"
实际上定义了一个新字符串),以确保你永远不会忘记这一点。同时,您决定将另一张便条别在冰箱上,告诉您之前将便条放在哪里(list.add(...)
)可能是个好主意。
有时,您会在冰箱上看到这个并决定追踪您的笔记 ( list.get(0)
)。然后你意识到你真的不再需要提醒了,因为你手里拿着这张纸条,所以你把它从冰箱里拿出来了(list.remove(0)
)。你手里还拿着什么?
我想它会更清楚,当你准确地写出你的代码中发生的事情时,没有省略任何步骤:
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);