前言
HashMap是一個(gè)散列表,它存儲(chǔ)的內(nèi)容是鍵值對(duì)(key-value)映射。
1 定義
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
}
由HashMap定義可以看出
1) HashMap<K,V>表示支持泛型
2)繼承自AbstractMap抽象類,實(shí)現(xiàn)對(duì)于Map容器的操作方法。
3)實(shí)現(xiàn)Map接口,實(shí)現(xiàn)Map接口中定義的諸多方法。
4)實(shí)現(xiàn)Cloneable接口,
5)實(shí)現(xiàn)Serializable接口,保證容器的可序列化。
2 屬性值
HashMap的屬性值含義已在代碼注釋中給出。
//默認(rèn)初始化容量大小,必須為2的冪的數(shù),初始為16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量值
static final int MAXIMUM_CAPACITY = 1 << 30;
//默認(rèn)負(fù)載因子為0.75,代表table的填充度
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//鏈表長度閾值,HashMap采用數(shù)組+鏈表形式存儲(chǔ)
//當(dāng)鏈表長度過長影響查詢效率,因此當(dāng)鏈表長度超過此值時(shí),鏈表轉(zhuǎn)為紅黑樹形式存儲(chǔ),以提升效率。
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
//樹最小容量
static final int MIN_TREEIFY_CAPACITY = 64;
//存儲(chǔ)節(jié)點(diǎn)的數(shù)組
transient Node<K,V>[] table;
transient Set<Map.Entry<K,V>> entrySet;
// 容器中鍵值對(duì)的數(shù)目
transient int size;
transient int modCount;
//閾值,超過閾值則需要擴(kuò)容
int threshold;
//負(fù)載因子
final float loadFactor;
//節(jié)點(diǎn)數(shù)據(jù)結(jié)構(gòu)
static class Node<K,V> implements Map.Entry<K,V> {
//哈希值
final int hash;
//鍵值
final K key;
//對(duì)應(yīng)元素值
V value;
//指向下一個(gè)節(jié)點(diǎn)
Node<K,V> next;
//構(gòu)造方法
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
3 構(gòu)造方法
1) 無參數(shù)
//采用默認(rèn)值初始化
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
2)初始化容量為initialCapacity
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
3)初始化容量為initialCapacity,負(fù)載因子為loadFactor
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
this.threshold = tableSizeFor(initialCapacity);
}
4)使用集合初始化
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
//遍歷集合,將集合中元素添加到this容器中
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
4 核心方法
| 方法 | 含義 | 時(shí)間復(fù)雜度 |
|---|---|---|
| get(Object key) | 根據(jù)key獲取value | O(1) |
| put(K key, V value) | 存儲(chǔ)鍵值對(duì) | O(1) |
| containsKey(Object key) | 是否包含key | O(n) |
| containsValue(Object value) | 是否包含value | O(n) |
| remove(Object key) | 刪除key對(duì)應(yīng)的value | O(n) |
| size() | 容器元素?cái)?shù)目 | O(1) |
| isEmpty() | 集合是否為空 | O(1) |
| clear() | 清空集合 | O(n) |
5 put()方法
put()方法添加鍵值對(duì)。在分析put()過程中會(huì)發(fā)現(xiàn)HashMap中有紅黑樹的實(shí)現(xiàn)過程。HashMap是采用數(shù)組加鏈表的方式存儲(chǔ)數(shù)據(jù)的,當(dāng)鏈表長度過長時(shí)影響查找效率,因此當(dāng)鏈表長度超過一定閾值時(shí),將鏈表結(jié)構(gòu)轉(zhuǎn)為紅黑樹存儲(chǔ),提升查找效率。
//添加鍵為key,值為value
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//添加鍵值對(duì)的方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
//使用到的中間變量
Node<K,V>[] tab; Node<K,V> p; int n, i;
//如果當(dāng)前數(shù)組為空,或者表長度為0,調(diào)用resize()方法重新分配容量
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 如果數(shù)組中對(duì)應(yīng)的索引位置的節(jié)點(diǎn)p為空,即不存在沖突情況,直接將鍵值對(duì)存儲(chǔ)在索引為i位置。
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//若存在沖突,則需要遍歷鏈表尋找添加位置
else {
Node<K,V> e; K k;
//如果節(jié)點(diǎn)p的鍵值與待存儲(chǔ)節(jié)點(diǎn)的鍵值相同,將p節(jié)點(diǎn)賦給e節(jié)點(diǎn)
//后面會(huì)對(duì)e幾點(diǎn)進(jìn)行判斷,如果不為空,則將e節(jié)點(diǎn)的值賦值為value,采用替換的方式存儲(chǔ)新的鍵值對(duì),保證key的不可重復(fù)。
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
// 如果p節(jié)點(diǎn)的類型是TreeNode,,說明此時(shí)p節(jié)點(diǎn)所處的鏈表已經(jīng)轉(zhuǎn)為紅黑樹存儲(chǔ)的方式。則調(diào)用紅黑樹的添加節(jié)點(diǎn)方法,添加新的節(jié)點(diǎn)
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//p節(jié)點(diǎn)的鍵不重復(fù),且當(dāng)前仍采用鏈表形式存儲(chǔ) ,則遍歷p節(jié)點(diǎn)為頭節(jié)點(diǎn)的鏈表
else {
//鏈表的遍歷,binCount記錄鏈表的長度
for (int binCount = 0; ; ++binCount) {
//查到到鏈表尾
if ((e = p.next) == null) {
// 將新鍵值對(duì)創(chuàng)建的節(jié)點(diǎn)插在鏈表尾
p.next = newNode(hash, key, value, null);
// 判斷鏈表長度有沒有過長,超過限定值,若超過,則需改為紅黑樹的形式存儲(chǔ)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
// treeifyBin的作用在于將鏈表結(jié)構(gòu)改為紅黑樹存儲(chǔ)
treeifyBin(tab, hash);
break;
}
// 在遍歷鏈表過程中發(fā)現(xiàn)了有相同key的節(jié)點(diǎn),則采用替換方式。
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果e節(jié)點(diǎn)不為空,說明存在相同key,則替換此節(jié)點(diǎn)的value,并返回舊的value
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
//更新鍵值對(duì)數(shù)目,并判斷是否需要擴(kuò)容。
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//resize方法進(jìn)行重新分配容量
final Node<K,V>[] resize() {
//獲取舊表
Node<K,V>[] oldTab = table;
//舊表為空oldCap=0,否則oldCap = 舊表長度
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 存儲(chǔ)舊閾值
int oldThr = threshold;
int newCap, newThr = 0;
//舊表不為空
if (oldCap > 0) {
// 原數(shù)組長度大于最大容量(1073741824) 則將threshold設(shè)為Integer.MAX_VALUE=2147483647
// 接近MAXIMUM_CAPACITY的兩倍
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
//沒有達(dá)到最大容量,則容量擴(kuò)大二倍,同時(shí)閾值擴(kuò)大二倍
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
// 如果原來的thredshold大于0則將容量設(shè)為原來的thredshold
// 在第一次帶參數(shù)初始化時(shí)候會(huì)有這種情況
newCap = oldThr;
else { // zero initial threshold signifies using defaults
// 在默認(rèn)無參數(shù)初始化會(huì)有這種情況
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
// loadFactor 哈希負(fù)載因子 默認(rèn)0.75,可在初始化時(shí)傳入,16*0.75=12 可以放12個(gè)鍵值對(duì)
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
//設(shè)置新的臨界值
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
//擴(kuò)容操作,創(chuàng)建新的容量大小的數(shù)組newTab
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
// 如果原來的table有數(shù)據(jù),則將數(shù)據(jù)復(fù)制到新的table中
if (oldTab != null) {
// for循環(huán)遍歷舊數(shù)組
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)//如果當(dāng)前節(jié)點(diǎn)不存在下一個(gè)節(jié)點(diǎn),即此節(jié)點(diǎn)為存儲(chǔ)在數(shù)組中的節(jié)點(diǎn)
//將節(jié)點(diǎn)e添加至數(shù)組索引為e.hash & (newCap - 1)的位置。
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)//如果節(jié)點(diǎn)e是TreeNode
// 如果e節(jié)點(diǎn)時(shí)紅黑樹的節(jié)點(diǎn),則調(diào)用TreeNode的split()方法
// 由于紅黑樹的知識(shí)也是比較復(fù)雜,本篇中不做過多解釋。這里只說明樹的各類方法的作用。split()方法是拆分紅黑樹,以實(shí)現(xiàn)節(jié)點(diǎn)的重新映射。
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // 如果e節(jié)點(diǎn)是鏈表中的節(jié)點(diǎn),則實(shí)現(xiàn)鏈表的復(fù)制
//鏈表的復(fù)制操作,即將舊表中的含有e節(jié)點(diǎn)的鏈表復(fù)制到新表中
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;
}
}
}
}
}
//返回?cái)U(kuò)容后的新表
return newTab;
}
6 get()方法
get()方法根據(jù)鍵值獲取元素值.
public V get(Object key) {
Node<K,V> e;
//查找鍵值為key的節(jié)點(diǎn),查找成功返回value值,否則返回null。
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
//檢查集合不為空,將first指向第一個(gè)節(jié)點(diǎn)
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
//查找到節(jié)點(diǎn),返回節(jié)點(diǎn)
return first;
if ((e = first.next) != null) {
// 如果節(jié)點(diǎn)e類型為紅黑樹的節(jié)點(diǎn)類型,則調(diào)用getTreeNode()方法返回節(jié)點(diǎn)。getTreeNode()方法是完成紅黑樹的查找操作。
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
// 如果節(jié)點(diǎn)e為普通類型的節(jié)點(diǎn),則遍歷鏈表查找
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
//沒有查找到返回null
return null;
}
7 contains()方法
//判斷是否包含鍵key
public boolean containsKey(Object key) {
//同樣采用getNode方法進(jìn)行查找,查找結(jié)果不為null則說明存在
return getNode(hash(key), key) != null;
}
//是否包含value
public boolean containsValue(Object value) {
Node<K,V>[] tab; V v;
if ((tab = table) != null && size > 0) {
for (int i = 0; i < tab.length; ++i) {
for (Node<K,V> e = tab[i]; e != null; e = e.next) {
if ((v = e.value) == value ||
(value != null && value.equals(v)))
return true;
}
}
}
return false;
}
8 remove()方法
@Override
public boolean remove(Object key, Object value) {
return removeNode(hash(key), key, value, true, true) != null;
}
//刪除節(jié)點(diǎn)
final Node<K,V> removeNode(int hash, Object key, Object value,
boolean matchValue, boolean movable) {
Node<K,V>[] tab; Node<K,V> p; int n, index;
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
Node<K,V> node = null, e; K k; V v;
//查找節(jié)點(diǎn)操作
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
node = p;
else if ((e = p.next) != null) {
// 紅黑樹的節(jié)點(diǎn)查找
if (p instanceof TreeNode)
node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
else {
//鏈表的節(jié)點(diǎn)查找
do {
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
}
}
if (node != null && (!matchValue || (v = node.value) == value ||
(value != null && value.equals(v)))) {
//查找到的節(jié)點(diǎn)為紅黑樹節(jié)點(diǎn),則調(diào)用紅黑樹的刪除節(jié)點(diǎn)方法
if (node instanceof TreeNode)
((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
else if (node == p)
// 查找到的節(jié)點(diǎn)屬于數(shù)組table中的元素,則直接將tab中的元素重新賦值
tab[index] = node.next;
else
//鏈表的節(jié)點(diǎn)賦值
p.next = node.next;
++modCount;
//更新數(shù)目
--size;
afterNodeRemoval(node);
return node;
}
}
return null;
}
9 小結(jié)
HashMap采用數(shù)組+鏈表的方式存儲(chǔ)鍵值對(duì),當(dāng)鏈表長度超過限定閾值,則將鏈表結(jié)構(gòu)調(diào)整為紅黑樹,提高查找效率。通過源碼可以看出在添加鍵值對(duì)時(shí)沒有null檢查,因此HashMap是允許null值的。
10 對(duì)比
1) HashMap允許將null作為一個(gè)entry的key或者value,而Hashtable不允許。
2) 由于HashMap非線程安全,Hashtable是線程安全的。
3)HashMap增加了紅黑樹。