wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes i am able to insert a duplicate key in a map implementation. Not able to understand why? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "i am able to insert a duplicate key in a map implementation. Not able to understand why?" Watch "i am able to insert a duplicate key in a map implementation. Not able to understand why?" New topic
Author

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

preethi kumar
Ranch Hand

Joined: Jun 04, 2010
Posts: 50

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



Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1449
    
    6

Are you actually able to insert? No, right. It will replace that key's value with the new value, so in your case 81.


Swastik
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4343
    
    8

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

Joined: Jun 04, 2010
Posts: 50
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

Joined: Jan 08, 2009
Posts: 1449
    
    6

You can use an iterator over the map to get the key and value.

preethi kumar
Ranch Hand

Joined: Jun 04, 2010
Posts: 50
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

Joined: Jun 04, 2010
Posts: 50
Thanks Swastik :-)
Swastik Dey
Rancher

Joined: Jan 08, 2009
Posts: 1449
    
    6

You are most welcome.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38007
    
  22
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

Joined: Jun 04, 2010
Posts: 50
Thanks Campbell sir :-)
 
Don't get me started about those stupid light bulbs.
 
subject: i am able to insert a duplicate key in a map implementation. Not able to understand why?
 
Similar Threads
Hashcode program error
I need nested hashmap program(hashmap of hashmap).
multiple synchronized block in class..
Why the same sequence from HashMap, HashTable, HashSet in Java Collections?
About thread safe...