對於Map接口來說,它有倆種比較重要的實現類HashMap和HashTable,它們保存元素的時候,都是無序的。但是,它們也有一定的區別,適用於不同的情況。
HashTable相對於HashMap更早提出,應用也非常廣泛,HashMap後來提出是爲了代替HashTable的類,也就是說建議使用HashMap,不要使用HashTable。可能我們覺得HashTable很好用,爲什麼不用呢?這裏簡單分析一下它們的區別:
1.HashTable的方法時同步的,HashMap不能同步,所以在多線程場合要使用HashTable,這個區別就像Vector與ArrayList一樣
2.HashTable不允許null值(key和value都不可以),HashMap允許null值(key與value都可以)。
3.HashTab有一個contains()方法,功能和containsValue()功能一樣。
4.HashTable使用Enumeration遍歷,而HashMap使用Iterator進行遍歷
5.HashTable中hash數組默認大小是11,增加的方式是:old*2+1,HashMap中hash數組的默認大小是16,而且一定是2的指數。
6.哈希值的使用不同,HashTable直接使用對象的hashCode,而HashMap會重新計算hash值。
示例代碼:
public class Test4 {
public static void main(String[] args) {
Map<String, String>map=new HashMap<>();
map.put("1", "a");
map.put("2", "b");
map.put("3", "c");
for (String key : map.keySet()) {
//用get方法來獲取value
System.out.println(key+":"+map.get
(key));
}
}
}
結果如下:
3:c
2:b
1:a
說明:HashMap更符合Java集合框架的設計思路,更推薦使用。