Adding the same key twice to the card

I did Map research, and I found that if I add the same key twice, the map size remains the same. What is the technical reason for this?

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

Code to retrieve ...

 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 
+7
source share
3 answers

Because the contract of the card is that the keys must be unique. Therefore, if you associate a new value with an existing key, it will override the value of the existing record, rather than creating a new record:

An object that maps keys to values. The card cannot contain duplicate keys; each key can display no more than one value.

You can also check Map # put () javadoc (my highlight):

Associates the specified value with the specified key on this card (optional operation). If the map previously contained a key mapping, the old value is replaced with the specified value. (It is assumed that map m contains a mapping for key k if and only if m.containsKey (k) returns true.)

+22
source

A standard Java map can have only one value for each key. Note that this value can be a collection, and therefore you can effectively store multiple values ​​for each key.

If you need several identical keys on a card, there are various solutions. For example, see Guava Multimap .

+2
source

If the new key matches any of the existing keys, then the value on the card is overwritten.

0
source

All Articles