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

ID : 10352

viewed : 27

Tags : javahashmaphashtablejava

Top 5 Answer for java - What happens when a duplicate key is put into a HashMap?

vote vote

96

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

vote vote

80

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.

vote vote

74

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 one null 
vote vote

63

It replaces the existing value in the map for the respective key. And if no key exists with the same name then it creates a key with the value provided. eg:

Map mymap = new HashMap(); mymap.put("1","one"); mymap.put("1","two"); 

OUTPUT key = "1", value = "two"

So, the previous value gets overwritten.

vote vote

51

The prior value for the key is dropped and replaced with the new one.

If you'd like to keep all the values a key is given, you might consider implementing something like this:

import org.apache.commons.collections.MultiHashMap; import java.util.Set; import java.util.Map; import java.util.Iterator; import java.util.List; public class MultiMapExample {     public static void main(String[] args) {       MultiHashMap mp=new MultiHashMap();       mp.put("a", 10);       mp.put("a", 11);       mp.put("a", 12);       mp.put("b", 13);       mp.put("c", 14);       mp.put("e", 15);       List list = null;        Set set = mp.entrySet();       Iterator i = set.iterator();       while(i.hasNext()) {          Map.Entry me = (Map.Entry)i.next();          list=(List)mp.get(me.getKey());           for(int j=0;j<list.size();j++)          {           System.out.println(me.getKey()+": value :"+list.get(j));          }       }    } } 

Top 3 video Explaining java - What happens when a duplicate key is put into a HashMap?

Related QUESTION?