Reputation: 87
when we put a <key,value>
in a HashMap,if the key is already present in the HashMap then the value gets replaced. But if for a key the value is itself a HashMap then would it get replaced with the HashMap?
Upvotes: 0
Views: 569
Reputation: 17319
If I understand what you're asking, you want to know if what you just said will cause a memory leak (please update your question if this isn't what you're asking).
If you do:
Map<?, ?> m = new HashMap<Object, Object>();
m.put(m, m);
Then m
will ultimately only contain a reference to itself. Because of how Java's GC works via an object reference graph, and because they use an algorithm which tracks visited nodes during a GC sweep, if nothing maintains a reference to m
, then m
will be garbage collected, despite containing a reference to itself. Circular references are perfectly handled in the Java GC.
If m
is placed into a field (i.e., not a local variable declared inside a method) then it's a different story.
m
is placed in a static
field, then there will always be a reference to it from a GC root, which means it won't be reclaimed. Note: nothing strongly referenced to from a static
field will ever be garbage collected.m
is placed in a member field (non-static
), then the map won't be garbage collected until the object that contains it is garbage collected.m
, then m
won't be garbage collected until all those references are either a) part of an object that can be garbage collected or b) are set to null
or some other value to no longer refer to m
.TL;DR the garbage collector handles circular object references just fine.
Sidenote: Please update your question with information, don't just add it as comments to your question or others' answers.
Upvotes: 1
Reputation: 5537
The wording in your question is a bit opaque, but a HashMap<HashMap, Object>
is perfectly valid (if somewhat strange). In that case, if:
HashMap map = new HashMap<HashMap<String, String>, String>();
HashMap a = new HashMap<String, String>();
HashMap b = new HashMap<String, String>(); //a.equals(b) == true
map.put(a, "foo"); //map.get(a) would now return "foo"
map.put(b, "bar"); //original entry is replaced, map.get(a) would now return "bar"
Upvotes: 0
Reputation: 691893
Yes, it would be replaced. Remember that a Map only stores references to other objects.
You put a reference to a HashMap in a map, and the map keeps a reference to this HashMap.
If you put a reference to another HashMap using the same key, the reference to the first put HashMap is replaced by the reference to the new HashMap. The type of the object doesn't matter. It always works the same way.
Upvotes: 8