What happens when a duplicate key is put into a HashMap? What happens when a duplicate key is put into a HashMap? java java

What happens when a duplicate key is put into a HashMap?


By definition, the put command replaces the previous value associated with the given key in the map (conceptually like an array indexing operation for primitive types).

The map simply drops its reference to the value. If nothing else holds a reference to the object, that object becomes eligible for garbage collection. Additionally, Java returns any previous value associated with the given key (or null if none present), so you can determine what was there and maintain a reference if necessary.

More information here: HashMap Doc


You may find your answer in the javadoc of Map#put(K, V) (which actually returns something):

public V put(K key,             V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for this 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.)

Parameters:
key - key with which the specified value is to be associated.
value - value to be associated with the specified key.

Returns:
previous value associated with specified key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with the specified key, if the implementation supports null values.)

So if you don't assign the returned value when calling mymap.put("1", "a string"), it just becomes unreferenced and thus eligible for garbage collection.


it's Key/Value feature and you could not to have duplicate key for several values because when you want to get the actual value which one of values is belong to entered key
in your example when you want to get value of "1" which one is it ?!
that's reasons to have unique key for every value but you could to have a trick by java standard lib :

import java.util.ArrayList;import java.util.HashMap;import java.util.Map;public class DuplicateMap<K, V> {    private Map<K, ArrayList<V>> m = new HashMap<>();    public void put(K k, V v) {        if (m.containsKey(k)) {            m.get(k).add(v);        } else {            ArrayList<V> arr = new ArrayList<>();            arr.add(v);            m.put(k, arr);        }    }     public ArrayList<V> get(K k) {        return m.get(k);    }    public V get(K k, int index) {        return m.get(k).size()-1 < index ? null : m.get(k).get(index);    }}


and you could to use it in this way:

    public static void main(String[] args) {    DuplicateMap<String,String> dm=new DuplicateMap<>();    dm.put("1", "one");    dm.put("1", "not one");    dm.put("1", "surely not one");    System.out.println(dm.get("1"));    System.out.println(dm.get("1",1));    System.out.println(dm.get("1", 5));}

and result of prints are :

[one, not one, surely not one]not onenull