一、基本介紹
HashMap和Hashtable都是Java中的集合類,它們的主要功能是存儲鍵值對。HashMap和Hashtable有很多共同點,但是也存在一些區別。
二、線程安全性
Hashtable是線程安全的,而HashMap是非線程安全的。由於Hashtable支持多線程同時寫入數據,因此保證了線程安全,在多線程應用中比較常用;而HashMap在多線程情況下,需要使用同步機制來保證線程安全,否則會出現數據不一致的問題。
Hashtable示例:
Hashtable hashtable = new Hashtable(); hashtable.put(1, "Java");
HashMap示例:
Map hashMap = new HashMap(); hashMap.put(1, "Java");
三、鍵和值的null值
Hashtable中,如果鍵值為null或者value為null,會直接拋出NullPointerException異常。而HashMap允許鍵為null值,也允許值為null。
Hashtable示例:
Hashtable hashtable = new Hashtable(); hashtable.put(null, "Java");//會拋出NullPointerException異常 hashtable.put(1, null);//會拋出NullPointerException異常
HashMap示例:
Map hashMap = new HashMap(); hashMap.put(null, "Java");//可以正常插入 hashMap.put(1, null);//可以正常插入
四、迭代器
Hashtable的枚舉器(Enumerator)只允許在集合初始化時使用,而不允許在修改過程中使用。而HashMap的迭代器(Iterator)是fail-fast迭代器,可以在並發時拋出ConcurrentModificationException異常。
Hashtable示例:
Hashtable hashtable = new Hashtable(); Enumeration keys = hashtable.keys(); while (keys.hasMoreElements()) { Integer key = keys.nextElement(); System.out.println(key + ":" + hashtable.get(key)); } //在修改hash表的過程中,使用keys都會拋出異常
HashMap示例:
Map hashMap = new HashMap(); Iterator iterator = hashMap.keySet().iterator(); while (iterator.hasNext()) { Integer key = iterator.next(); System.out.println(key + ":" + hashMap.get(key)); } hashMap.put(2, "C++"); iterator.next();//拋出ConcurrentModificationException異常
五、性能
Hashtable和HashMap的性能問題,主要是因為桶的初始值問題所導致的。Hashtable默認初始值是11,而HashMap默認初始值是16。
Hashtable示例:
Hashtable hashtable = new Hashtable(); long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { hashtable.put(i, "Java"); } long end = System.currentTimeMillis(); System.out.println("Hashtable put 1000000 elements consumes: " + (end - start) + " ms.");
HashMap示例:
Map hashMap = new HashMap(); long start = System.currentTimeMillis(); for (int i = 0; i < 1000000; i++) { hashMap.put(i, "Java"); } long end = System.currentTimeMillis(); System.out.println("HashMap put 1000000 elements consumes: " + (end - start) + " ms.");
六、總結
通過以上對HashMap和Hashtable的比較,我們可以知道HashMap比Hashtable更為常用,因為HashMap不僅性能更好,而且允許鍵值對為空值。當然,如果需要在多線程的環境下使用,就需要使用Hashtable。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/182470.html