HashTable 和 HashMap 在 Java 中的區別


以下是 Java 中 HashTable 和 HashMap 類之間的主要區別。

 HashTableHashMap
同步HashTable 同步。HashMap 未同步。
執行緒安全HashTable 是執行緒安全的。HashMap 不是執行緒安全的。
Null 物件HashTable 不允許 null 鍵或 null 值。HashMap 允許一個 null 鍵和多個 null 值。
效能HashTable 較快。HashMap 比 HashTable 慢。
自 Java 版本1.21.5

示例

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class Tester {
   public static void main(String args[]) {

      Map<String, String> map = new HashMap<String, String>();

      map.put("1", "One");
      map.put("2", "Two");
      map.put("3", "Three");
      map.put("5", "Five");
      map.put("6", "Six");

      System.out.println("HashMap: " + map);

      Map<String, String> map1 = new Hashtable<String, String>();
   
      map1.put("1", "One");
      map1.put("2", "Two");
      map1.put("3", "Three");
      map1.put("5", "Five");
      map1.put("6", "Six");

      System.out.println("HashTable: " + map1);
   }
}

輸出

HashMap: {1 = One, 2 = Two, 3 = Three, 5 = Five, 6 = Six}
HashTable: {6 = Six, 5 = Five, 3 = Three, 2 = Two, 1 = One}

更新於: 21-Jun-2020

3K+ 人次瀏覽

開啟您的 事業

完成課程並獲得認證

立即開始
廣告
© . All rights reserved.