HashMaphtml
hashmap本質數組+鏈表+紅黑樹(鏈地址法,解決hash衝突問題)。根據key取得hash值,而後計算出數組下標,若是多個key對應到同一個下標,就用鏈表串起來,新插入的在前面。java
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
^ 亦或:兩個數轉爲二進制,而後從高位開始比較,若是相同則爲0,不相同則爲1。node
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) //最多容納的Entry數,若是當前元素個數多於這個就要擴容 }
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 && (first = tab[(n - 1) & hash]) != null) { 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); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
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; //擴充空表 //&:兩個數都轉爲二進制,而後從高位開始比較,若是兩個數都爲1則爲1,不然爲0。取最小 if ((p = tab[i = (n - 1) & hash]) == null) //p取hash鏈頭,並判斷是否已存在hash鏈 tab[i] = newNode(hash, key, value, null); //賦值-新hash鏈 else { //存在hash鏈,hash鏈中key值不惟一 Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) //p同key e = p; //取原值 else if (p instanceof TreeNode) //紅黑樹 鏈長>8 e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { //從錶鏈中取數據e:p的下一個;判斷是否有p之外(其餘k)的Node p.next = newNode(hash, key, value, null); //插入新值 if (binCount >= TREEIFY_THRESHOLD - 1) // 8-1 treeifyBin(tab, hash); /** TREEIFY_THRESHOLD * 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. */
//超過數量裝換list爲tree break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) //e同key 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; /** modCount * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */
//fail-fast 機制是java集合(Collection)中的一種錯誤機制。當多個線程對同一個集合的內容進行操做時,就可能會產生fail-fast事件。
//內部結構發生變化指的是結構發生變化,例如put新鍵值對,可是某個key對應的value值被覆蓋不屬於結構變化 //if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
static final int tableSizeFor(int cap) { //10 int n = cap - 1; //9 n |= n >>> 1; //13 n |= n >>> 2; //15 n |= n >>> 4;//15 n |= n >>> 8;//15 n |= n >>> 16;//15 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;//16 //10(1001+0001)—— 16(1111+0001) 即位數補滿1再+1
final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; // (The javadoc description is true upon serialization. // Additionally, if the table array has not been allocated, this // field holds the initial array capacity, or zero signifying // DEFAULT_INITIAL_CAPACITY(16).) —— 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;
/** * Indicates that the named compiler warnings should be suppressed in the * annotated element (and in all program elements contained in the annotated * element). Note that the set of warnings suppressed in a given element is * a superset of the warnings suppressed in all containing elements. For * example, if you annotate a class to suppress one warning and annotate a * method to suppress another, both warnings will be suppressed in the method. * * <p>As a matter of style, programmers should always use this annotation * on the most deeply nested element where it is effective. If you want to * suppress a warning in a particular method, you should annotate that * method rather than its class. * * @author Josh Bloch * @since 1.5 * @jls 4.8 Raw Types * @jls 4.12.2 Variables of Reference Type * @jls 5.1.9 Unchecked Conversion * @jls 5.5.2 Checked Casts and Unchecked Casts * @jls 9.6.3.5 @SuppressWarnings */ @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE}) @Retention(RetentionPolicy.SOURCE) public @interface SuppressWarnings {...}
@SuppressWarnings({"rawtypes","unchecked"})
//SuppressWarnings壓制警告,即去除警告 rawtypes是說傳參時也要傳遞帶泛型的參數
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; //按二進制取各位最小值,重算hash值,擴容*2-1即高位+1
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) { //連續性分奇偶,在hash中,初值爲0
//好比 oldCap = 9 —— 1001&0001=0001;1001&0010=0000;1001&0011=0001;1001&0100=0000;1001&0101=0001;1001&0110=0000; if (loTail == null) loHead = e; // else loTail.next = e; //爲當前next賦值 loTail = e;//尾指針,輔助下一次next的賦值
} else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null);
//times:1—hi—next=2,e=1;hiHead=hiTail=e=1;loHead=loTail=null;
//times:2—lo—next=3,e=2;hiHead=hiTail=e=1;loHead=loTail=loTail.next=2;
//times:3—hi—next=4,e=3;hiTail=hiTail.next=3;loHead=loTail=loTail.next=2;
//times:4—lo—next=5,e=4;hiTail=hiTail.next=3;loTail=loTail.next=4;
//hiHead=1;loHead=2;hiHead.next.next=2.next=loHead.next=3 if (loTail != null) { loTail.next = null; newTab[j] = loHead;//奇數一列 } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead;//偶數一列 } } } } } return newTab; }
線程安全性數組
HashMap是線程不安全的安全
public class HashMapInfiniteLoop { private static HashMap<Integer,String> map = new HashMap<Integer,String>(2,0.75f); public static void main(String[] args) { map.put(5, "C"); new Thread("Thread1") { public void run() { map.put(7, "B"); System.out.println(map); }; }.start(); new Thread("Thread2") { public void run() { map.put(3, "A); System.out.println(map); }; }.start(); } }
thread1和thread2都觸發了resize擴容。此時爲5(1)、7(1)、3(1) 假設hash是mod2app
擴容後結果應分別是0:{},1:{5,3},2:{},3:{7}oop
考慮到並行,假設thread1阻塞在resize的next = e.next;(while ((e = next) != null)循環中) ,此時e=5, 5.next=7,7.next=3
thread2擴容完成,此時5.next=3,3.next=null,7.next=null源碼分析
thread1回調:e不變爲5,但此時next=5.next=3,3.next=null;即0:{},1:{5},2:{0},3:{3}this
好像會漏數據但不至於閉環? 不安全體如今沒有鎖spa
參考:
HashMap實現原理及源碼分析-http://www.cnblogs.com/chengxiao/p/6059914.html
HashMap和ConcurrentHashMap淺析-http://blog.csdn.net/zldeng19840111/article/details/6703104
Java中的幾個HashMap/ConcurrentHashMap實現分析-http://www.importnew.com/19685.html
Java8系列之從新認識HashMap-http://www.importnew.com/20386.html
JDK1.8HashMap原理和源碼分析-https://max.book118.com/html/2016/1215/72615285.shtm