当我们尝试在 Java 中的 HashMap 对象中添加重复键时会发生什么?

javaobject oriented programmingprogramming

HashMap 是一个实现 Map 接口的类。它基于哈希表。它允许空值和空键。

您可以在 HashMap 对象中存储键值对。这样做后,您可以检索相应键的值,但我们用于键的值应该是唯一的

重复值

put 命令将值与指定的键关联。即,如果我们添加一个键值对,其中键已经存在,则此方法将用新值替换键的现有值,

示例

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();
      }
   }
}

输出

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

相关文章