當我們嘗試在 Java 中向 HashMap 物件中新增重複鍵時會發生什麼?


HashMap 是一個實現 Map 介面的類。它基於雜湊表。它允許 null 值和 null 鍵。

您可以在 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

更新於: 15-10-2019

4K+ 瀏覽量

啟動你的 職業生涯

完成課程以獲得認證

開始
廣告