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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With