简体   繁体   English

不明白为什么Set不为null

[英]Don't understand why Set is not null

I suppose the answer is straightforward but I don't see explanation. 我想答案很简单,但我没有看到解释。

Map<String, Set<String>> m = new HashMap<String, Set<String>>();
Set<String> a = new HashSet<String>();

a.add("a");
a.add("b");
a.add("c");

m.put("set", a); // reference    
a = null; // if I type a.remove("b"); variable m holds only a and c as it should

System.out.println(m.get("set")); // Why this prints [a, b, c] as it should null or empty

You have 1 set and 2 references to the set ( a and the reference inside the map). 你有1套和2套参考集( a和地图内的参考)。

You set one reference to null, but that doesn't mean all the other references would be set to null. 您将一个引用设置为null,但这并不意味着所有其他引用都将设置为null。

Imagine you're pointing at someone and I'm pointing at the same person. 想象一下,你指着某人,我指着同一个人。 Just because you stop pointing, doesn't mean I'll stop pointing. 仅仅因为你停止指点,并不意味着我会停止指点。

Once the reference inside the map is removed, the set is eligible for garbage collection. 删除映射中的引用后,该集合符合垃圾回收的条件。

You are setting the local variable to null not the reference inside the Map. 您将局部变量设置为null而不是Map中的引用。

If you want to set both to null you have simple remove the Set from the Map. 如果要将两者都设置为null,则可以从地图中删除Set。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM