Java中HashMap和Hashtable之间的区别
Hashtable是原始java.util的一部分,是Dictionary的具体实现。但是,Java2重新设计了Hashtable,使其也实现了Map接口。因此,哈希表现在已集成到集合框架中。它类似于HashMap,但已同步。
像HashMap一样,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[]) {
//创建一个哈希映射
HashMap hm = new HashMap();
//将元素放入映射
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));
//获取一组条目
Set set = hm.entrySet();
//获取一个迭代器
Iterator i = set.iterator();
//显示元素
while(i.hasNext()) {
Map.Entry me = (Map.Entry)i.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
System.out.println();
//将1000存入Zara的帐户
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