What happens when we try to add a duplicate key into a HashMap object in java?


The HashMap is a class that implements the Map interface. It is based on the Hash table. It allows null values and null keys.

You can store key-value pairs in the HashMap object. Once you do so you can retrieve the values of the respective keys but, the values we use for keys should be unique

Duplicate values

The put command associates the value with the specified key. i.e. if we add a key-value pair where the key exists already, this method replaces the existing value of the key with the new value,

Example

 Live Demo

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DuplicatesInHashMap {
   public static void main(String args[]) {
      HashMap<String, Long> map = new HashMap<String, Long>();
      map.put("Krishna", 9000123456L);
      map.put("Rama", 9000234567L);
      map.put("Sita", 9000345678L);
      map.put("Bhima", 9000456789L);
      map.put("Yousuf ", 9000456789L);
      System.out.println("Values Stored . . . . . .");
      //Retrieving the values of a Hash map
      Iterator it1 = map.entrySet().iterator();
      System.out.println("Contents of the hashMap are: ");
      while(it1.hasNext()){
         Map.Entry <String, Long> ele = (Map.Entry) it1.next();
         System.out.print(ele.getKey()+" : ");
         System.out.print(ele.getValue());
         System.out.println();
      }
      map.put("Bhima", 0000000000L);
      map.put("Rama", 0000000000L);
      //Retrieving the values of a Hash map
      Iterator it2 = map.entrySet().iterator();
      System.out.println("Contents of the hashMap after inserting new key-value pair: ");
      while(it2.hasNext()){
         Map.Entry <String, Long> ele = (Map.Entry) it2.next();
         System.out.print(ele.getKey()+" : ");
         System.out.print(ele.getValue());
         System.out.println();
      }
   }
}

Output

Values Stored . . . . . .
Contents of the hashMap are:
Yousuf : 9000456789
Krishna : 9000123456
Sita : 9000345678
Rama : 9000234567
Bhima : 9000456789
Contents of the hashMap after inserting new key-value pair:
Yousuf : 9000456789
Krishna : 9000123456
Sita : 9000345678
Rama : 0
Bhima : 0
raja
Published on 15-Oct-2019 10:31:10
Advertisements