Could anyone explain me what happen behind the scenes when a duplicate value is put into HashMap
?
put(k1,v1)
put(k2,v1)
How does it effect the memory?
Could anyone explain me what happen behind the scenes when a duplicate value is put into HashMap
?
put(k1,v1)
put(k2,v1)
How does it effect the memory?
Absolutely nothing special happens. A new entry is created and inserted somewhere in the underlying structure based on the entry's key. The value of a HashMap
entry has no bearing on where the entry is placed or how it is retrieved.
To clarify, the value will be copied in each HashMap
Entry
.
Maybe you are confused about what that value is. First, make the distinction between objects, reference values, and variables. The value we've been talking about is a reference to an object. Read this to understand how that applies.
HashMap
doesn't care about values. It doesn't check them. It only cares about keys. So when you put the same value
map.put(k1,v1);
map.put(k2,v1);
the HashMap
will construct two Entry
objects, which will both hold (and therefore copy) the value of v1
, and store those in its underlying structure.