user1579492
user1579492

Reputation: 163

adding the same key twice in the Map

I was doing research on Maps and I discovered that if I add the same key twice deliberately then the size of the Map remains the same. What's the technical reason behind this?

 Map map=new HashMap();//HashMap key random order.
         map.put("Amit","Java");
         map.put("Amit","Java");

Code for retrieving...

System.out.println("There are "+map.size()+" elements in the map.");
         System.out.println("Content of Map are...");
         Set s=map.entrySet();
         Iterator itr=s.iterator();
         while(itr.hasNext())
         {
             Map.Entry m=(Map.Entry)itr.next();
             System.out.println(m.getKey()+"\t"+m.getValue()+"\t"+ m.hashCode());
          }

The result that I get:

There are 1 elements in the map.
Content of Map are...
Amit    Java    3943477

Upvotes: 10

Views: 33065

Answers (3)

Akhi
Akhi

Reputation: 2242

If the new key is same as any of the existing keys, then the value in the map is overwritten.

Upvotes: 0

Brian Agnew
Brian Agnew

Reputation: 272257

A standard Java Map can only have one value per key. Note that that value could be a collection, and thus you can effectively store multiple values per key.

If you want multiple identical keys in a map, various solutions exist. See the Guava Multimap, for example.

Upvotes: 2

assylias
assylias

Reputation: 328598

Because Map's contract is that keys must be unique. So if you associate a new value to an existing key, it will override the value of the existing entry, not create a new entry:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

You can also check Map#put() javadoc (emphasis mine):

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

Upvotes: 27

Related Questions