Java 中 HashMap 和 Hashtable 的差异


Hashtable 是 java.util 的一部分,是 Dictionary 的具体实现。但是,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-6-2020

超过 1 千次浏览

启动您的 职业

完成课程并获得认证

开始学习
广告
© . All rights reserved.