HashMap和HashTable詳解
本文以JDK1.8原始碼為例。
一、HashMap底層結構
HashMap底層採用陣列+單向連結串列+紅黑樹實現,結構示意圖如下:
下面我們結合原始碼對此圖進行說明。HashMap類繼承自Map介面,有如下三種構造方法:
第一種:
/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ public HashMap(int initialCapacity, float loadFactor){ ...... }
該構造方法建立HashMap時可以指定HashMap的初始容量(initialCapacity)和載入因子(loadFactor)。
第二種:
/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); }
該構造方法可以指定HashMap的初始容量,而載入因子使用預設值DEFAULT_LOAD_FACTOR=0.75。
第三種:
/** * 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 }
該構造方法建立的HashMap使用預設的初始容量和載入因子,分別為16和0.75,原始碼如下:
/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
現在我們我們使用第三種方式構建一個自己的HashMap,並向其中加入一個(key,value)鍵值對,會發生什麼?
Map<Integer,String> map = new HashMap<>();
map.put(1,null);
第一行程式碼構建了一個空的map,此時裡面什麼都沒有。第二行程式碼通過呼叫put方法向其中加入一個鍵值對(1,null)(HashMap允許向其中加入key=null或value=null的鍵值對,而HashTable則不可以,這也是兩者的一個不同點)。put方法原始碼如下:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
put方法呼叫了putVal方法,第一個引數計算key的hash值,原始碼如下:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果陣列為空或者沒有元素,呼叫resize方法擴容
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//根據要put進去的鍵值對的hash尋找陣列下標i
//如果下標i的位置沒有資料建立Node直接放入
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//如果下標i的位置有資料
else {
//e用來儲存map與要put的資料的key相同的資料
Node<K,V> e; K k;
//下標i位置的資料和要put進去的資料的key相同時,將資料賦給中間變數e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//下標i位置資料是紅黑樹,使用紅黑樹的插入方式,將資料放入紅黑樹中
//將紅黑樹中key相同的資料賦給中間變數e
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//下標i位置資料是單向連結串列
else {
//遍歷單向連結串列,將要put進去的資料放入連結串列的末尾
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果連結串列長度達到TREEIFY_THRESHOLD=8,將連結串列轉換成紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//找到與要put進去的資料相同的key的資料儲存到e中
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//找到了與put資料相同key的資料e時,更新key對應的value值
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
putVal原始碼基本思路:
1、新增第一個鍵值對之前,對空的map先擴容,容量大小為16,載入因子為0.75;
2、通過鍵值對(key,value)中key的hash值,尋找陣列下標i,根據下標位置是否有資料,分兩種情況:
(1)下標對應的位置沒有資料,通過鍵值對(key,value)直接建立一個Node<Integer,String>,放入該位置;
(2)下標對應位置有資料,分兩種情況(單個節點也可以看成是連結串列)
a、資料是Node<Integer,String>構成的連結串列,將資料插入連結串列的末尾,並判斷此時連結串列長度是否達到8,如果達到,將連結串列轉換成紅黑樹;同時,將與插入資料具有相同key的資料臨時取出
c、資料是紅黑樹,按紅黑樹的插入方式,將資料插入;同時,將與插入資料具有相同key的資料臨時取出
(3)前面兩步中,如果map中已經存在相同key的資料,則實際上不會進行插入資料,而是根據臨時取出的資料更新value值。
n = (tab = resize()).length;
呼叫如下resize方法進行擴容:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
程式碼執行
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
到這裡,我們就明白了示意圖中黃色虛線內的16個小方框的真正含義了。其實就是一個長度為16的Node<Integer,String>型別的陣列。
那麼載入因子又是怎麼回事?載入因子是用來設定擴容時機的。比如0.75,那麼當陣列填滿超過16*0.75=12時,map自動擴容為原來的2倍,也就是32。下一次當陣列填滿超過32*0.75=24個時,擴容為64,以此類推……。那麼為何不是填滿16個再擴容呢?回答這個問題,我們先看資料是怎麼放入陣列中的。檢視putVal方法,我們看到鍵值對放入map中需要計算key的hash值,原始碼如下:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
這裡為了說明方便,我們做一個假設:假設hash方法是key對某個整數取模,比如12。剛才我們放入的一個鍵值對(1,null),應該是按如下過程進行的。首先,擴容,形成容量為16的陣列。然後計算1的hash值為hash(1)=1%12=1,找到下標為1的位置,對應示意圖中的第二個小方框,因為該方框中還沒有資料,直接將資料放入。同理鍵值對(0,"h")會放入第一個小方框中。那麼鍵值對(13,"apple")和(1,"hello")又如何存放?我們先看(13,"apple"),因為hash(13)=13%12=1,找到陣列下標1,但是下標1的位置已經放入了(1,null),這裡就發生了衝突(稱為hash碰撞),但是刪除掉這個資料肯定不合適,所以(13,"apple")會以連結串列的形式新增在(1,null)的末尾。同理(1,"hello")放入的位置也是第二個小方框,前面我們看到putVal方法中有一個引數onlyIfAbsent,在被呼叫時設定成了false,意思是遇到相同的key,更新value值,所以null值會被更新為hello。如果發生碰撞的資料很多,比如(25,"h"),(37,"h"),(49,"h"),(61,"h")……這樣的鍵值對都需要放入下標為1的位置,如果每次都是新增在連結串列的末尾,會形成非常長的連結串列,這樣查詢效率會非常低。為了提高查詢效率,HashMap採取了另外一種思路,當下標位置的元資料個數達到一定閾值時(預設為8),採用紅黑樹儲存,原始碼如下:
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
*/
static final int TREEIFY_THRESHOLD = 8;
也就是說當下標1的位置到達8個元素時,單向連結串列轉換成紅黑樹,如示意圖所示。我們再回到載入因子的問題,載入因子越大,填滿的元素越多,空間利用率越高,但衝突的機會加大了。例如假設載入因子為1,擴容的閾值為16*1=16,也就是說只有當陣列全部填滿才會再次擴容,顯然空間利用率很高,但是當填滿了15個時,再次插入資料時,hash碰撞的概率高達15/16(不一定準確,因為具體hash演算法不明確),碰撞機率很大,會容易形成連結串列和紅黑樹,查詢資料變慢。反之,載入因子越小,填滿的元素越少,衝突的機會減小,但空間浪費多了。例如載入因子為1/16。擴容的閾值為16*1/16=1,也就是填進一個元素就要擴容,當然會浪費空間,因陣列的容量變大,hash碰撞的機率會變小。所以載入因子過大和過小都不好,因此,必須在 "衝突的機率"與"空間利用率"之間尋找一種平衡與折衷,所以預設載入因子0.75較好(不是最好)。
二、HashMap和HashTable區別
官方文件原文如下:
* Hash table based implementation of the <tt>Map</tt> interface. This
* implementation provides all of the optional map operations, and permits
* <tt>null</tt> values and the <tt>null</tt> key. (The <tt>HashMap</tt>
* class is roughly equivalent to <tt>Hashtable</tt>, except that it is
* unsynchronized and permits nulls.) This class makes no guarantees as to
* the order of the map; in particular, it does not guarantee that the order
* will remain constant over time.
HashMap和HashTable基本等價,有兩點不同:
(1)permits nulls
HashMap允許鍵值對是空值的情況,而HashTable不可以。前面已經提到。測試如下:
package com.leboop;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Map.Entry;
public class HashMapTest {
public static void main(String[] args) {
//初始化map和table
Map<Integer,String> map = new HashMap<>();
Map<Integer,String> table = new Hashtable<>();
//向map新增key=null,value=null,正常執行
map.put(null, null);
//正常輸出1
System.out.println(map.size());
//向table中新增key=null,捕獲到空指標異常
try{
table.put(null, "hello");
}catch(NullPointerException e){
//輸出:key空指標異常:java.lang.NullPointerException
System.out.println("key空指標異常:"+e);
}
map.put(1,null);
map.put(2,null);
/**
* 輸出:
* null=null
* 1=null
* 2=null
*/
for(Entry<Integer, String> e:map.entrySet()){
System.out.println(e.getKey()+"="+e.getValue());
}
try{
table.put(1, null);
}catch(NullPointerException e){
//value空指標異常:java.lang.NullPointerException
System.out.println("value空指標異常:"+e);
}
}
}
(2)unsynchronized
HashMap不能非同步,也就是說執行緒不安全,而HashTable是執行緒安全的,HashTable的部分原始碼如下:
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}
// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
public synchronized V remove(Object key) {
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> e = (Entry<K,V>)tab[index];
for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
if ((e.hash == hash) && e.key.equals(key)) {
modCount++;
if (prev != null) {
prev.next = e.next;
} else {
tab[index] = e.next;
}
count--;
V oldValue = e.value;
e.value = null;
return oldValue;
}
}
return null;
}
HashTable中的方法基本都有關鍵字synchronized。但是HashMap中並沒有synchronized,我們先看一段測試程式碼:
package com.leboop;
import java.util.HashMap;
import java.util.Map;
public class Difference {
private static Map<String, String> map=new HashMap<>();
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
Thread t = new Thread("執行緒" + i){
public void run() {
double i = Math.random() * 100000;
map.put("鍵" + i, "值" + i);
map.remove("鍵" + i);
System.out.println(Thread.currentThread().getName() + " size = " + map.size());
}
};
t.start();
}
}
}
輸出結果:
執行緒24 size = 0
執行緒23 size = 0
執行緒11 size = 0
執行緒12 size = 2
執行緒0 size = 1
執行緒20 size = 0
執行緒26 size = 0
執行緒3 size = 1
執行緒15 size = 1
執行緒1 size = 1
執行緒17 size = 1
執行緒6 size = 0
執行緒21 size = 0
執行緒22 size = 0
執行緒27 size = 0
執行緒25 size = 0
執行緒4 size = 1
執行緒29 size = 0
執行緒10 size = 1
執行緒8 size = 1
執行緒9 size = 2
執行緒2 size = 1
執行緒5 size = 1
執行緒32 size = 0
執行緒7 size = 2
執行緒43 size = 0
執行緒35 size = 2
執行緒41 size = 0
執行緒18 size = 2
執行緒19 size = 4
執行緒16 size = 0
執行緒37 size = 0
執行緒14 size = 1
執行緒13 size = 2
執行緒30 size = 0
執行緒36 size = 0
執行緒42 size = 0
執行緒40 size = 0
執行緒39 size = 0
執行緒31 size = 1
執行緒28 size = 0
執行緒53 size = 1
執行緒44 size = 0
執行緒46 size = 0
執行緒52 size = 0
執行緒50 size = 0
執行緒51 size = 0
執行緒49 size = 0
執行緒45 size = 0
執行緒47 size = 0
執行緒34 size = 0
執行緒48 size = 0
執行緒33 size = -1
執行緒38 size = -1
執行緒54 size = -1
執行緒56 size = -1
執行緒59 size = -1
執行緒57 size = -1
執行緒58 size = -1
執行緒60 size = -1
執行緒63 size = -1
執行緒55 size = -1
執行緒64 size = -1
執行緒62 size = -1
執行緒61 size = -1
執行緒65 size = -1
執行緒66 size = -1
執行緒67 size = -1
執行緒68 size = -1
執行緒69 size = -1
執行緒70 size = -1
執行緒71 size = -1
執行緒72 size = -1
執行緒73 size = -1
執行緒74 size = -1
執行緒75 size = -1
執行緒76 size = -1
執行緒77 size = -1
執行緒78 size = -1
執行緒79 size = -1
執行緒80 size = -1
執行緒81 size = -1
執行緒82 size = -1
執行緒84 size = -1
執行緒83 size = -1
執行緒85 size = -1
執行緒86 size = -1
執行緒87 size = -1
執行緒88 size = -1
執行緒89 size = -1
執行緒90 size = 0
執行緒91 size = -1
執行緒92 size = -1
執行緒93 size = -1
執行緒94 size = -1
執行緒95 size = -1
執行緒96 size = -1
執行緒97 size = -1
執行緒98 size = -1
執行緒99 size = -1
從輸出結果size=-1中顯而易見。執行緒操作資料的時候是從主存拷貝一個變數副本進行操作,這裡不再累述。