简体   繁体   English

在Map中添加两次相同的键

[英]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. 我正在研究Map ,我发现如果我故意两次添加相同的密钥,那么地图的大小保持不变。 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. 因为Map的合同是密钥必须是唯一的。 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): 你也可以查看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.) (当且仅当m.containsKey(k)返回true时,地图m才包含密钥k的映射。)

A standard Java Map can only have one value per key. 标准Java Map每个键只能有一个值。 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. 例如,请参阅Guava Multimap

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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