我想答案很简单,但我看不到任何解释。
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
最佳答案
您有 1 个集合和 2 个对该集合的引用(a
和 map 中的引用)。
您将一个引用设置为 null,但这并不意味着所有其他引用都将设置为 null。
想象一下,您指着某人,而我指着同一个人。仅仅因为你停止指点,并不意味着我会停止指点。
一旦映射中的引用被删除,该集合就可以进行垃圾回收。
关于java - 不明白为什么 Set 不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30190913/