1.put方法
1.把存入元素用hashcode產(chǎn)生hash值然后用hash%table.length取余產(chǎn)生數(shù)組下標(biāo)
2.當(dāng)插入元素hash相同時(shí),存入數(shù)組某個(gè)元素的鏈表中,
從頭部存入。然后把新插入的元素移動(dòng)一下,使得get獲得值變成最后put的元素
HashMap中的put方法
//閾值(java1.8中和1.7中不太一樣)
this.threshold = tableSizeFor(initialCapacity);
//返回大于等于傳入數(shù)字的二的次方數(shù)
static final int tableSizeFor(int cap) {
int n = cap - 1;//減一的原因是擔(dān)心直接輸入二的次方數(shù),類似4,8,16
n |= n >>> 1;//二進(jìn)制右移一位進(jìn)行或運(yùn)算
n |= n >>> 2;//右移最大只有16位是因?yàn)閕nt類型最大32位
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
//最后得到的數(shù)字應(yīng)該全部是一
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
//判斷是否大于最大容量,不是的話加1就是結(jié)果
}
//8bit(位)=1Byte(字節(jié))一位在內(nèi)存中有一個(gè)格子
//1024Byte(字節(jié))=1KB
//1024KB=1MB
//1024MB=1GB
//異或運(yùn)算,相同為0不同為1
//put方法第一步:初始化tab
n = (tab = resize()).length;
//第二步算出當(dāng)前插入元素的數(shù)組下標(biāo),看這個(gè)下標(biāo)的內(nèi)部元素
//是否為空,如果為空就new Node
if ((p = tab[i = (n - 1) & hash]) == null)
//如果不是空,先新建兩個(gè)變量,就執(zhí)行以下三個(gè)判斷
Node<K,V> e; K k;
//第一步判斷當(dāng)前結(jié)點(diǎn)key和插入的key是否一致,一致就把當(dāng)前結(jié)點(diǎn)p賦值e
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//否則的話判斷p結(jié)點(diǎn)的類型是否是一個(gè)TreeNode
//紅黑樹(shù)方法
//插入紅黑樹(shù)
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
//否則的話就走鏈表類型
for (int binCount = 0; ; ++binCount) {
//如果當(dāng)前結(jié)點(diǎn)的下一個(gè)結(jié)點(diǎn)是空,
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//判斷當(dāng)前鏈表處的結(jié)點(diǎn)數(shù)量是否大于TREEIFY_THRESHOLD(8)大于的話就轉(zhuǎn)換為一個(gè)紅黑樹(shù),當(dāng)?shù)诰艂€(gè)來(lái)的時(shí)候樹(shù)化
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//遍歷鏈表判斷當(dāng)前結(jié)點(diǎn)是否找到,找到停止循環(huán),把e賦值給p
if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
//如果已經(jīng)存在key,則把以前的value替換成新value,并把老的值return回去
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)e.value = value;
afterNodeAccess(e);
return oldValue;
}
//上面的代碼進(jìn)行完還沒(méi)有return就修改次數(shù)加一,判斷是否需要擴(kuò)容
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
treeifyBin(tab, hash)轉(zhuǎn)紅黑樹(shù)代碼
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//判斷是否為空,或者是否小于64,MIN_TREEIFY_CAPACITY值為64,擴(kuò)容或者初始化
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();//重新計(jì)算下標(biāo),減短鏈表
//判斷當(dāng)前數(shù)組下標(biāo)是否為空,不為空樹(shù)化
else if ((e = tab[index = (n - 1) & hash]) != null) {
//樹(shù)化代碼
//遍歷鏈表的每一個(gè)元素
TreeNode<K,V> hd = null, tl = null;
do {
//new 一個(gè)treeNode結(jié)點(diǎn)
TreeNode<K,V> p = replacementTreeNode(e, null);
//然后把鏈表變成一個(gè)雙向鏈表!!!!!!!
if (tl == null)
hd = p;
else {
p.prev = tl;
tl.next = p;
}
tl = p;
} while ((e = e.next) != null);
//把雙向鏈表變?yōu)榧t黑樹(shù)
if ((tab[index] = hd) != null)
hd.treeify(tab);
}
}
//new 一個(gè)treeNode
TreeNode<K,V> replacementTreeNode(Node<K,V> p, Node<K,V> next) {
return new TreeNode<>(p.hash, p.key, p.value, next);
}
關(guān)于treeNode解釋
紅黑樹(shù)里面的一個(gè)結(jié)點(diǎn)
TreeNode<K,V> parent; // 父節(jié)點(diǎn)
TreeNode<K,V> left;
TreeNode<K,V> right;
TreeNode<K,V> prev; //雙向鏈表
boolean red;
treeify(tab)為TreeNode內(nèi)的一個(gè)方法
final void treeify(Node<K,V>[] tab) {
TreeNode<K,V> root = null;
//遍歷鏈表
for (TreeNode<K,V> x = this, next; x != null; x = next) {
next = (TreeNode<K,V>)x.next;
x.left = x.right = null;
//判斷root是否為空,為空把第一個(gè)結(jié)點(diǎn)變成頭結(jié)點(diǎn)
if (root == null) {
x.parent = null;
x.red = false;
root = x;
}
else {
K k = x.key;
int h = x.hash;
Class<?> kc = null;
for (TreeNode<K,V> p = root;;) {
int dir, ph;
K pk = p.key;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0)
dir = tieBreakOrder(k, pk);
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
x.parent = xp;
if (dir <= 0)
xp.left = x;
else
xp.right = x;
//把x結(jié)點(diǎn)插入紅黑樹(shù),調(diào)整紅黑樹(shù)
root = balanceInsertion(root, x);
break;
}
}
}
}
//至此形成一個(gè)紅黑樹(shù),下面把根節(jié)點(diǎn)移動(dòng)到散列表位置
//備注:轉(zhuǎn)換過(guò)程保留雙向鏈表,規(guī)則,紅黑樹(shù)的根節(jié)點(diǎn)是雙向鏈表的頭結(jié)點(diǎn),所以使用雙向鏈表
moveRootToFront(tab, root);
}
獲得一個(gè)對(duì)象的hash值方法
identityHashCode()
插入紅黑樹(shù)方法putTreeVal
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
int h, K k, V v) {
Class<?> kc = null;
boolean searched = false;
TreeNode<K,V> root = (parent != null) ? root() : this;
for (TreeNode<K,V> p = root;;) {
int dir, ph; K pk;
if ((ph = p.hash) > h)
dir = -1;
else if (ph < h)
dir = 1;
else if ((pk = p.key) == k || (k != null && k.equals(pk)))
return p;
else if ((kc == null &&
(kc = comparableClassFor(k)) == null) ||
(dir = compareComparables(kc, k, pk)) == 0) {
if (!searched) {
TreeNode<K,V> q, ch;
searched = true;
if (((ch = p.left) != null &&
(q = ch.find(h, k, kc)) != null) ||
((ch = p.right) != null &&
(q = ch.find(h, k, kc)) != null))
return q;
}
dir = tieBreakOrder(k, pk);
}
TreeNode<K,V> xp = p;
if ((p = (dir <= 0) ? p.left : p.right) == null) {
Node<K,V> xpn = xp.next;
TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
if (dir <= 0)
xp.left = x;
else
xp.right = x;
xp.next = x;
x.parent = x.prev = xp;
if (xpn != null)
((TreeNode<K,V>)xpn).prev = x;
moveRootToFront(tab, balanceInsertion(root, x));
return null;
}
}
}
擴(kuò)容resize
//size代表當(dāng)前map數(shù)據(jù)總量
if (++size > threshold)
resize();
afterNodeInsertion(evict);
下面方法包括擴(kuò)容和初始化
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;
//以上內(nèi)容均為數(shù)組初始化,以下內(nèi)容為擴(kuò)容
if (oldTab != null) {
//遍歷老數(shù)組上面的每個(gè)元素
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//表示當(dāng)前數(shù)組位置元素只有一個(gè)元素
if (e.next == null)
//把e元素放入新數(shù)組中(計(jì)算新數(shù)組下標(biāo))
newTab[e.hash & (newCap - 1)] = e;
//如果e是紅黑樹(shù)里面的一個(gè)結(jié)點(diǎn)
else if (e instanceof TreeNode)
//紅黑樹(shù)擴(kuò)容,傳hashmap自己,和新數(shù)組,和老數(shù)組當(dāng)前位置數(shù)組元素,和老數(shù)組
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//如果為鏈表,進(jìn)行擴(kuò)容
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
//遍歷鏈表每個(gè)元素
do {
next = e.next;
//用當(dāng)前結(jié)點(diǎn)的hash值和老數(shù)組對(duì)象的hash值進(jìn)行與運(yùn)算,
//只有兩個(gè)結(jié)果,0/1,把所有鏈表元素遍歷一遍,就將一個(gè)長(zhǎng)鏈表拆分成兩個(gè)鏈表
if ((e.hash & oldCap) == 0) {
if (loTail == null)//上面運(yùn)算等于0的就是low低位數(shù)組
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)//等于1就是高位數(shù)組
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
//遍歷結(jié)束
loTail.next = null;
newTab[j] = loHead;//把low組放進(jìn)前面
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;//把high組接著放
}
}
}
}
}
return newTab;
}
//紅黑樹(shù)擴(kuò)容將樹(shù)箱中的節(jié)點(diǎn)拆分為上下樹(shù)箱,
//或取消樹(shù)化(如果現(xiàn)在太小)。僅從調(diào)整大小調(diào)用,bit為原數(shù)組大小
final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
TreeNode<K,V> b = this;
// Relink into lo and hi lists, preserving order
//新建兩個(gè)子樹(shù)
TreeNode<K,V> loHead = null, loTail = null;
TreeNode<K,V> hiHead = null, hiTail = null;
int lc = 0, hc = 0;
for (TreeNode<K,V> e = b, next; e != null; e = next) {
next = (TreeNode<K,V>)e.next;
e.next = null;
if ((e.hash & bit) == 0) {
if ((e.prev = loTail) == null)
loHead = e;
else
loTail.next = e;
loTail = e;
++lc;
}
else {
if ((e.prev = hiTail) == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
++hc;
}
}
if (loHead != null)
//如果低位子樹(shù)元素個(gè)數(shù)小于六個(gè),進(jìn)行把樹(shù)轉(zhuǎn)化為單向鏈表
if (lc <= UNTREEIFY_THRESHOLD)
tab[index] = loHead.untreeify(map);
else {
tab[index] = loHead;
//如果高位數(shù)組如果是空,不需要調(diào)整樹(shù),以前的就行
//如果高位數(shù)組為空,則需要重新樹(shù)化,調(diào)整為平衡二叉樹(shù)
if (hiHead != null) // (else is already treeified)
loHead.treeify(tab);
}
}
if (hiHead != null) {
//如果高位子樹(shù)元素個(gè)數(shù)小于六個(gè),進(jìn)行把樹(shù)轉(zhuǎn)化為鏈表
if (hc <= UNTREEIFY_THRESHOLD)
tab[index + bit] = hiHead.untreeify(map);
else {
tab[index + bit] = hiHead;
if (loHead != null)
hiHead.treeify(tab);
}
}
}
//整個(gè)源碼
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)
tab[i] = newNode(hash, key, value, null);
else {
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)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
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;
p = e;
}
}
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;
}
2.get方法
public V get(Object key) {
Node<K,V> e;
//三元運(yùn)算
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;
if ((tab = table) != null && (n = tab.length) > 0 &&
//查找需要查找的key在散列表的數(shù)組中的位置,并且把當(dāng)前數(shù)組元素賦給first,判斷這個(gè)位置元素是否為空
//(n-1) & hash 作用是計(jì)算數(shù)組索引下標(biāo)
(first = tab[(n - 1) & hash]) != null) {
//檢驗(yàn)大數(shù)組第一個(gè)結(jié)點(diǎn)的key
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
//第二個(gè)結(jié)點(diǎn),如果是二叉樹(shù)就調(diào)用地下方法
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
//如果不是,樹(shù),那就是一個(gè)鏈表,然后遍歷鏈表判斷key和哪個(gè)相等
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}