简体   繁体   中英

adding the same key twice in the Map

I was doing research on Map s 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

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

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.

如果新密钥与任何现有密钥相同,则映射中的值将被覆盖。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM