为什么打印输出不为空?

时间:2013-05-06 09:16:13

标签: java list arraylist null

为什么会这样?

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

控制台说:aaa

有人可以帮我解释一下吗?我认为控制台应该是null,它应该是吗?

4 个答案:

答案 0 :(得分:5)

不,因为您将列表中的值存储在s中。因此,"aaa"的引用位于列表和s中,在您从列表中删除后,s仍然引用它。

答案 1 :(得分:1)

没有。它按预期工作。 S仍然引用"aaa"。您只更改了列表,而不是S

答案 2 :(得分:1)

String s = list.get(0);

您将引用保存到s,然后打印了它的值。有什么问题?

List#remove更改了列表,而不是变量ss仍然引用了"aaa"

您可能想要切换订单:

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

答案 3 :(得分:1)

让我把它写进一个故事:

你自己写了一个说“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);