Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i am able to insert a duplicate key in a map implementation. Not able to understand why?

 
preethi kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

my question is why am i not getting compilation error? since the Map implementations should not allow duplicate keys



 
Swastik Dey
Rancher
Posts: 1603
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you actually able to insert? No, right. It will replace that key's value with the new value, so in your case 81.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Firstly, if this was an error it wouldn't be a compiler error. The compiler doesn't know that a Map doesn't contain duplicates. If it was an error, it would have to be at runtime.

But it's not an error anyway. There's nothing wrong with adding the same key more than once. It just won't store it more than once. If you look at the documentation for java.util.Map#put(K, V), it says:

If the map previously contained a mapping for the key, the old value is replaced by the specified value.
 
preethi kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your quick reply!!

One more question is how do we know which is the "key" and which is the "Value" in a Map ??
 
Swastik Dey
Rancher
Posts: 1603
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use an iterator over the map to get the key and value.

 
preethi kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The confusion is because both the "key" and "value" are objects! so how do we know which one is the "key" and which one is the "value"??
 
preethi kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Swastik :-)
 
Swastik Dey
Rancher
Posts: 1603
5
Android Java Java ME
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are most welcome.
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
preethi kumar wrote: . . . how do we know which one is the "key" and which one is the "value"??
By looking in the documentation, where you can work it out from the parameters shown. That link also answers your original question.
 
preethi kumar
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Campbell sir :-)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic