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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP