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