HashMap是非常常的集合類,我們來看下它的源碼(基于JDK1.8)。
支持原創(chuàng),轉(zhuǎn)載請注明出處。
繼承關(guān)系
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
HashMap實(shí)現(xiàn)了Map接口
核心成員變量
static final float DEFAULT_LOAD_FACTOR = 0.75f; //默認(rèn)裝載因子
final float loadFactor; //裝載因子
transient Node<K,V>[] table; //數(shù)組,作為Hash桶
節(jié)點(diǎn)內(nèi)部類
static class Node<K,V> implements Map.Entry<K,V> {
final int hash; //hash值
final K key; //鍵
V value; //值
Node<K,V> next; //指向hash值相同的下一個(gè)節(jié)點(diǎn)
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;
}
}
這個(gè)類封裝了鍵值對。
構(gòu)造方法
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; //使用默認(rèn)裝載因子
}
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);
}
添加元素:put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true); //在計(jì)算一個(gè)hash值
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null) //如果對應(yīng)的桶為空(無沖突),直接新建節(jié)點(diǎn),加入該桶
tab[i] = newNode(hash, key, value, null);
else { //存在Hash沖突
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode) //對應(yīng)桶的第一個(gè)元素是TreeNode節(jié)點(diǎn),說明鏈表過長,已轉(zhuǎn)換為紅黑樹
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); //將該節(jié)點(diǎn)放入紅黑樹中
else {
for (int binCount = 0; ; ++binCount) { //開啟循環(huán),遍歷鏈表
if ((e = p.next) == null) { //到達(dá)鏈表末尾,將元素加入尾部
p.next = newNode(hash, key, value, null); //加入尾部
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; //找到鏈表中一個(gè)元素和當(dāng)前節(jié)點(diǎn)hash值相同則跳出循環(huán)
p = e; //搜索下一個(gè)節(jié)點(diǎn)
}
}
if (e != null) { //存在一個(gè)鍵相同的節(jié)點(diǎn)
V oldValue = e.value; //保存舊的值
if (!onlyIfAbsent || oldValue == null)
e.value = value; //更新為新的值
afterNodeAccess(e);
return oldValue; //返回舊的值
}
}
++modCount;
if (++size > threshold)
resize(); //擴(kuò)容
afterNodeInsertion(evict);
return null;
}
put方法關(guān)鍵地方已經(jīng)注釋。首先根據(jù)key計(jì)算hash值,尋找桶,如果桶為空,則直接加入該桶,否則,將該元素加入紅黑樹或鏈表,這里就看下是如何加入鏈表的。首先遍歷鏈表,如果鏈表中某個(gè)節(jié)點(diǎn)和當(dāng)前元素的hash值相同,則更新節(jié)點(diǎn)的value值為當(dāng)前元素的value值,返回節(jié)點(diǎn)中原來的value值。如果搜索到鏈表尾部,直接將要加入的節(jié)點(diǎn)加入鏈表尾部。
查詢元素:get方法
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value; //計(jì)算hash值
}
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 &&
(first = tab[(n - 1) & hash]) != null) {//確定桶的下標(biāo),first指向桶的第一個(gè)元素
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first; //如果第一個(gè)元素和key的hash值相同,直接返回
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; //返回空
}
首先計(jì)算key的hash值,然后遍歷紅黑樹或鏈表返回hash值相同的節(jié)點(diǎn),都沒找到則返回空。
支持原創(chuàng),轉(zhuǎn)載請注明出處。
github:https://github.com/gatsbydhn