1

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?

Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
rayman
  • 18,586
  • 41
  • 135
  • 234
  • It's just like having the same value stored at two different indexes in an array. – khelwood Oct 05 '14 at 19:54
  • If that helps: Map can't have duplicate keys, there is no problem with having duplicate values. In other words `A->1` `B->1` is OK, but in case of `A->1` `A->2` map will store only one `A->..` pair, the most recently placed one. – Pshemo Oct 05 '14 at 20:07

1 Answers1

4

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.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 252,278
  • 54
  • 635
  • 683
  • So what are you saying? when two different keys has the same value. that value is actually being duplicated in the memory? or?? – rayman Oct 05 '14 at 19:47
  • 2
    @rayman Yes, that is what I am saying. The _value_ will be copied in each `HashMap` `Entry` and stored in the underlying structure. – Sotirios Delimanolis Oct 05 '14 at 19:49
  • @rayman: a *HashMap* is a mapping between a *Hashed* key, and a value. The value never gets hashed, only the key is. The uniqueness only affects keys. – Joel Oct 05 '14 at 20:26
  • Yes. but I am asking what will happen in the memory. will the value be duplicated? – rayman Oct 06 '14 at 07:30