都是基于哈希表提供鍵值映射的數(shù)據(jù)結(jié)構(gòu)
Hashtable是線程安全的,效率比較低,被廢棄的其他原因可能是因為Hashtable沒有遵循駝峰命名法吧 -----笑哭
繼承的父類不同
HashTable是繼承自Dictionary(已被廢棄)
HashMap是繼承自AbstractMap
不過它們都實現(xiàn)了同時實現(xiàn)了Map、Cloneable(可復(fù)制)、Serializable(可序列化)這三個接口
對Null Key 和 Null Value 的支持不同
Hashtable既不支持Null key也不支持Null value,當(dāng)key為Null時,調(diào)用put() 方法,就會拋出空指針異常。因為拿一個Null值去調(diào)用方法了。

當(dāng)value為null值時,Hashtable對其做了限制,也會拋出空指針異常。

HashMap中,null可以作為鍵,這樣的鍵只有一個;可以有一個或多個鍵所對應(yīng)的值為null。當(dāng)get()方法返回null值時,可能是HashMap中沒有該鍵,也可能使該鍵所對應(yīng)的值為null。因此,在HashMap中不能由get()方法來判斷HashMap中是否存在某個鍵, 而應(yīng)該用containsKey()方法來判斷
線程安全性不同
Hashtable是線程安全的,它的每個方法中都加入了Synchronize方法。在多線程并發(fā)的環(huán)境下,可以直接使用Hashtable,不需要自己為它的方法實現(xiàn)同步
HashMap不是線程安全的,在多線程并發(fā)的環(huán)境下,可能會產(chǎn)生死鎖等問題。使用HashMap時就必須要自己增加同步處理
雖然HashMap不是線程安全的,但是它的效率會比Hashtable要好很多。這樣設(shè)計是合理的。在我們的日常使用當(dāng)中,大部分時間是單線程操作的。HashMap把這部分操作解放出來了。當(dāng)需要多線程操作的時候可以使用線程安全的ConcurrentHashMap。ConcurrentHashMap雖然也是線程安全的,但是它的效率比Hashtable要高好多倍。因為ConcurrentHashMap使用了分段鎖,并不對整個數(shù)據(jù)進行鎖定
遍歷方式的內(nèi)部實現(xiàn)上不同
Hashtable、HashMap都使用了Iterator。而由于歷史原因,Hashtable還使用了Enumeration的方式
HashMap的Iterator是fail-fast迭代器。當(dāng)有其它線程改變了HashMap的結(jié)構(gòu)(增加,刪除,修改元素),將會拋出ConcurrentModificationException。不過,通過Iterator的remove()方法移除元素則不會拋出ConcurrentModificationException異常。但這并不是一個一定發(fā)生的行為,要看JVM
JDK8之前的版本,Hashtable是沒有fast-fail機制的。在JDK8及以后的版本中 ,HashTable也是使用fast-fail
初始容量大小和每次擴充容量大小的不同
Hashtable默認的初始大小為11,之后每次擴充,容量變?yōu)樵瓉淼?n+1
HashMap默認的初始化大小為16。之后每次擴充,容量變?yōu)樵瓉淼?倍
Hashtable會盡量使用素數(shù)、奇數(shù)。而HashMap則總是使用2的冪作為哈希表的大小。之所以會有這樣的不同,是因為Hashtable和HashMap設(shè)計時的側(cè)重點不同。Hashtable的側(cè)重點是哈希的結(jié)果更加均勻,使得哈希沖突減少。當(dāng)哈希表的大小為素數(shù)時,簡單的取模哈希的結(jié)果會更加均勻。
HashMap則更加關(guān)注hash的計算效率問題。在取模計算時,如果模數(shù)是2的冪,那么我們可以直接使用位運算來得到結(jié)果,效率要大大高于做除法。HashMap為了加快hash的速度,將哈希表的大小固定為了2的冪。當(dāng)然這引入了哈希分布不均勻的問題,所以HashMap為解決這問題,又對hash算法做了一些改動。這從而導(dǎo)致了Hashtable和HashMap的計算hash值的方法不同
計算hash值的方法不同
為了得到元素的位置,首先需要根據(jù)元素的key計算出一個hash值,然后再用這個hash值來計算得到最終的存儲位置
Hashtable直接使用對象的hashCode。hashCode是JDK根據(jù)對象的地址或者字符串或者數(shù)字算出來的int類型的數(shù)值。然后再使用除留余數(shù)法來獲得最終的位置。Hashtable在計算元素的位置時需要進行一次除法運算,而除法運算是比較耗時的
HashMap為了提高計算效率,將哈希表的大小固定為了2的冪,這樣在取模預(yù)算時,不需要做除法,只需要做位運算。位運算比除法的效率要高很多。為了解決這個問題,HashMap重新根據(jù)hashcode計算hash值后,又對hash值做了一些運算來打散數(shù)據(jù)。使得取得的位置更加分散,從而減少了hash沖突。當(dāng)然了,為了高效,HashMap只做了一些簡單的位處理(將得到的hash值與table的長度做位運算)。從而不至于把使用2 的冪次方帶來的效率提升給抵消掉
HashMap的工作原理
概述:HashMap是基于hashing的原理,使用put(key, value)存儲對象到HashMap中,使用get(key)從HashMap中獲取對象。當(dāng)調(diào)用put()方法傳遞鍵和值時,我們先對鍵調(diào)用hashCode()方法,返回的hashCode用于在Node數(shù)組table中找到bucket位置來儲存Entry對象。當(dāng)put新的儲存對象的鍵值key的hashCode與數(shù)組中已存在對象鍵值的hashCode相同(碰撞發(fā)生),如果兩個hashCode相等(equals),則判斷是否覆蓋(onlyIfAbsent參數(shù)值或已存在對象的value值為null),否則創(chuàng)建并存儲新的儲存對象,已存在存儲對象的next指針將指向新的存儲對象,形成拉鏈存儲結(jié)構(gòu)(JDK8還多了一重紅黑樹型結(jié)構(gòu)的判斷)

上圖就是HashMap中hash表的結(jié)構(gòu)示意圖,左側(cè)為儲存entry的Node數(shù)組table,當(dāng)發(fā)生碰撞以后,bucket相同但鍵值不相等的的entry就會以單向鏈表的形式鏈接起來
先揪出這幾個重要的屬性變量(源碼基于JDK1.8)
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold; // 下一次resize的時候擴容數(shù)組的長度
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor; // 負載因子大小 即數(shù)組容量達到負載因子大小時resize擴容
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table; // 儲存鍵值對象的數(shù)組
通常情況下使用默認的構(gòu)造方法創(chuàng)建HashMap
/**
* Constructs an empty <tt>HashMap</tt> with the default initial capacity
* (16) and the default load factor (0.75).
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
默認的負載因子(DEFAULT_LOAD_FACTOR)的值為 0.75,這是時間和空間成本上一種折中,增大負載因子可以減少 Hash 表(Entry 數(shù)組table)所占用的內(nèi)存空間,但會增加查詢數(shù)據(jù)的時間開銷,而查詢是最頻繁的的操作(HashMap 的 get() 與 put() 方法都要用到查詢);減小負載因子會提高數(shù)據(jù)查詢的性能,但會增加 Hash 表所占用的內(nèi)存空間
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*
* 此HashMap經(jīng)過結(jié)構(gòu)修改的次數(shù)結(jié)構(gòu)修改是指更改HashMap中映射數(shù)量或以其他方式修改其
* 內(nèi)部結(jié)構(gòu)(例如,重新散列)的修改。該字段用于使HashMap的Collection-views上的迭代器
* 失敗 翻譯直譯 - -!
*/
transient int modCount;
初始化過程中并沒有初始化table數(shù)組的初始長度
初始化之后就是往里面塞東西了,調(diào)用put(K key, V value)方法
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//這里進行了table的初始化操作
if ((tab = table) == null || (n = tab.length) == 0)
//當(dāng)table == null || tab.length == 0 的時候進行resize()擴容
n = (tab = resize()).length;
//按照HashMap減少沖突的規(guī)則查找當(dāng)前儲存對象對應(yīng)的bucket位置
if ((p = tab[i = (n - 1) & hash]) == null)
//如果當(dāng)前待儲存對象所對應(yīng)的bucket位置為null,放心大膽的直接把對象存進去
tab[i] = newNode(hash, key, value, null);
else {
//如果到了這里,恭喜你,產(chǎn)生碰撞了
//即表示通過鍵值hashCode處理后得到的bucket有重復(fù)
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
//如果碰撞的兩個key相等 這里需要對hashCode和equals有清晰的認識
//將已存在的鍵值對象賦值給新對象是用于后面判斷映射已存在
e = p;
else if (p instanceof TreeNode)
//碰撞鍵值的key不相等
//紅黑樹型結(jié)構(gòu)則直接將新插入的結(jié)點掛在樹上qwq
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
//碰撞鍵值的key不相等
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
//將已存在的對象指向新存儲對象
p.next = newNode(hash, key, value, null);
//如果表太小,調(diào)整大小,替換給定散列的索引處的bin中的所有鏈接節(jié)點
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
//找到鍵值相等的已儲存對象則退出
break;
//移動指針,直到找到最后一個已存儲的對象
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
//如果已存在對象的value值為空或者onlyIfAbsent = true則覆蓋舊的value值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
//沒有碰撞 初始化table或者直接往數(shù)組插入數(shù)據(jù)后
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
get(Object key)方法捶打一下
/**
* Returns the value to which the specified key is mapped,
* or {@code null} if this map contains no mapping for the key.
*
* <p>More formally, if this map contains a mapping from a key
* {@code k} to a value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise
* it returns {@code null}. (There can be at most one such mapping.)
*
* <p>A return value of {@code null} does not <i>necessarily</i>
* indicate that the map contains no mapping for the key; it's also
* possible that the map explicitly maps the key to {@code null}.
* The {@link #containsKey containsKey} operation may be used to
* distinguish these two cases.
*
* @see #put(Object, Object)
*/
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
//根據(jù)hashCode提取對應(yīng)的bucket位置
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
//bucket對應(yīng)的不是單一存儲對象,而是鏈表
//由此看見,當(dāng)bucket對應(yīng)單一存儲對象時,效率是最高的
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
感謝:
Java中的HashMap
HashMap 與HashTable的區(qū)別
HashMap與hashCode以及equals
HashMap實現(xiàn)原理分析
HashMap工作原理
HashMap的實現(xiàn)原理 HashMap底層實現(xiàn),hashCode如何對應(yīng)bucket?