JAVA中HashMap和Hashtable區別

Hashtable是基於陳舊的Dictionary類的,HashMap是Java 1.2引進的Map接口的一個實現,它們都是集合中將數據無序存放的。數組

1.Hashtable的方法是同步的,HashMap未經同步,因此在多線程場合要手動同步HashMap這個區別就像Vector和ArrayList同樣。
查看Hashtable的源代碼就能夠發現,除構造函數外,Hashtable的全部 public 方法聲明中都有 synchronized 關鍵字,而HashMap的源代碼中則連 synchronized 的影子都沒有,固然,註釋除外。多線程

2.Hashtable不容許 null 值(key 和 value 都不能夠),HashMap容許 null 值(key和value均可以)。函數

3.二者的遍歷方式大同小異,Hashtable僅僅比HashMap多一個elements方法。線程

Hashtable table = new Hashtable();  
table.put("key", "value");
Enumeration em = table.elements();  
while (em.hasMoreElements()) {  
   String obj = (String) em.nextElement();  
   System.out.println(obj);   
}

4.HashTable使用Enumeration,HashMap使用Iterator。code

從內部機制實現上的區別以下:
1.哈希值的使用不一樣,Hashtable直接使用對象的hashCode對象

int hash = key.hashCode();  
int index = (hash & 0x7FFFFFFF) % tab.length;

而HashMap從新計算hash值,並且用與代替求模:接口

int hash = hash(k);  
int i = indexFor(hash, table.length);  
  
static int hash(Object x) {  
  int h = x.hashCode();  
  
  h += ~(h << 9);  
  h ^= (h >>> 14);  
  h += (h << 4);  
  h ^= (h >>> 10);  
  return h;  
}  
  
static int indexFor(int h, int length) {  
  return h & (length-1);

2.Hashtable中hash數組默認大小是11,增長的方式是 old*2+1。HashMap中hash數組的默認大小是16,並且必定是2的指數。element

相關文章
相關標籤/搜索