简体   繁体   中英

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).

You set one reference to null, but that doesn't mean all the other references would be set to 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.

If you want to set both to null you have simple remove the Set from the Map.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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