Java 中 HashMap 和 Hashtable 的區別


**Hashtable** 是原始 java.util 的一部分,是字典的具體實現。但是,Java 2 重新設計了 Hashtable,使其也實現了 Map 介面。因此,Hashtable 現在已經整合到集合框架中。它與 HashMap 類似,但它是同步的。

與 HashMap 類似,Hashtable 將鍵值對儲存在雜湊表中。使用 Hashtable 時,您可以指定用作鍵的物件,以及要連結到該鍵的值。然後對鍵進行雜湊處理,並使用生成的雜湊碼作為將值儲存在表中的索引。

**HashMap** 類是基於雜湊表的 Map 介面的實現。

  • 此類不保證對映的迭代順序;特別是,它不保證該順序隨時間保持不變。
  • 此類允許空值和空鍵。

示例

即時演示

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMap_HashTable {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
     
      // Put elements to the map
      hm.put("Zara", new Double(3434.34));
      hm.put("Mahnaz", new Double(123.22));
      hm.put("Ayan", new Double(1378.00));
      hm.put("Daisy", new Double(99.22));
      hm.put("Qadir", new Double(-19.08));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
     
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      // Deposit 1000 into Zara's account
      double balance = ((Double)hm.get("Zara")).doubleValue();
      hm.put("Zara", new Double(balance + 1000));
      System.out.println("Zara's new balance: " + hm.get("Zara"));
      HashMap< String, String> hMap = new HashMap< String, String>();
      hMap.put("1", "1st");
      hMap.put("2", "2nd");
      hMap.put("3", "3rd");
      Collection cl = hMap.values();
      Iterator itr = cl.iterator();
      while (itr.hasNext()) {
         System.out.println(itr.next());
      }
   }
}

輸出

Daisy: 99.22
Ayan: 1378.0
Zara: 3434.34
Qadir: -19.08
Mahnaz: 123.22
Zara's new balance: 4434.34
1st
2nd
3rd

更新於:18-Jun-2020

1000+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告