Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 540
user1579492 Avatar asked Aug 06 '12 16:08

user1579492


2 Answers

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.)

like image 112
assylias Avatar answered Oct 15 '22 22:10

assylias


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.

like image 29
Brian Agnew Avatar answered Oct 15 '22 22:10

Brian Agnew