java面試題-2.容器之Map
阿新 • • 發佈:2022-02-10
8.HashMap原始碼分析?
底層:陣列+連結串列(雜湊表)
原始碼:
// 結點 transient Node<K,V>[] table; // 每個結點裡儲存的內容 static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; 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; } } static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; static final int MAXIMUM_CAPACITY = 1 << 30; static final float DEFAULT_LOAD_FACTOR = 0.75f; static final int TREEIFY_THRESHOLD = 8; static final int UNTREEIFY_THRESHOLD = 6; static final int MIN_TREEIFY_CAPACITY = 64; transient Set<Map.Entry<K,V>> entrySet; transient int size; transient int modCount; int threshold; final float 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); } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } // 向hash表中新增資料,即儲存物件的過程 public V put(K key, V value) { // 步驟一:呼叫key物件的hashcode()方法,獲得hashcode return putVal(hash(key), key, value, false, true); } // 步驟二:根據hashcode計算出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; // 起初,hash = hashcode % 陣列長度,但是,這種演算法由於使用了除法,效率低下,JDK後來改進了演算法,首先約定陣列長度必須為2的整數冪,這樣採用位運算即可實現取餘的效果:hash = hashcode & table.length - 1。 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); // 如果binCount大於等於8-1=7,就將當前連結串列轉變為紅黑樹,大大提高了效率 if (binCount >= TREEIFY_THRESHOLD - 1) treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; } 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; } else if (oldThr > 0) newCap = oldThr; else { 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) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { 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; } } } } } return newTab; } // 取資料過程 public V get(Object key) { Node<K,V> e; // 第一步:獲得key的hashcode,通過hash()雜湊演算法得到hash值,進而定位陣列的位置。 // 第三步:返回equals()為true的結點物件的value物件 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); // 第二步:在連結串列上挨個比較key物件,將key物件和連結串列上所有的結點的key物件比較,直到碰到返回true的結點物件為止 do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); } } return null; }
9.HashMap中的原始碼問題?
1. 陣列的元素型別是什麼?
Map.Entry介面的型別(key, value),
HashMap.Entry內部型別,實現了Map.Entry(key, value, next)
2. 為什麼要有連結串列?
計算每一對對映關係的key的hash值,然後根據hash值決定存到table陣列[index]
情況一:兩個key的hash值一樣,但是equals也不一樣--->index相同
情況二:兩個key的hash值不一樣,equals也不一樣,但是通過公式運算後--->index相同
那麼table[index]無法存放兩個物件,所以只能設計為連結串列的結構,把他們串起來。
3. 陣列的初始化的長度是多少?
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; 16
4. 陣列是否會擴容?
會
為什麼要擴容?
因為如果不擴容,會導致連結串列會變得很長,那麼它的查詢效率,新增的效率整個會降低。
什麼情況會擴容?
有一個變數threshold閾值來判斷是否需要擴容,當這個threshold達到臨界值時,就會考慮擴容,還要看當前新增(key, value)時,是否table[index]==null,
如果table[index]!=null,那麼就會擴容,如果table[index]為null,那麼本次先不擴容。
DEFAULT_LOAD_FACTOR,預設載入因子為0.75
threshold = table.length * 0.75
第一次:16 * 0.75 = 12,當我們size達到12個,就會考慮擴容。
在jdk1.8中擴容:
第一種:
當某個table[index]的連結串列的個數達到8個,並且table.length<64,那麼會擴容
第二種:
size >= threshold,並且table[index] != null
threshold = table.length * loadFator(預設值DEFAULT_LOAD_FACTOR:0.75)
5.index如何計算?
1.key是null,固定位置[index]=[0]
2.第一步,先用hashcode值通過hash(key)函式得到一個比較分散的"hash值"
第二步,再根據"hash值 & (table.length - 1)得到index在[0, length - 1]範圍內。
6.如何避免key重複?
如果key相同,用新值代替舊的值。
具體操作如下:
key相同,先判斷hash值,如果hash值相同,判斷key的地址或equals值是否相等。
7.新的(key,value)新增道table[index]後,發現table[index]不為空,如何連線?
在jdk1.7中,(key,value)是作為table[index]的頭,原來下面的元素作為當前(key,value)的next。
在jdk1.8中,直接連線到該連結串列的尾部。
8.為什麼要從JDK1.8之前的連結串列設計,修改為連結串列或紅黑樹的設計?
當某個連結串列比較長的時候,查詢效率會降低。為了提高查詢效率,那麼把table[index]下面的連結串列做調整。
如果table[index]的連結串列的結點的個數比較少,(8個或以內),就保持連結串列。如果超過8個,那麼就要考慮把連結串列轉為一顆紅黑樹。
TREEIFY_THRESHOLD:樹化閾值,從連結串列轉為紅黑樹的臨界值。
9.什麼時候樹化?
table[index]下的結點數一達到8個就樹化嗎?
如果table[index]的節點數量已經達到8個了,還要判斷table.length是否達到64,如果沒有達到64,先擴容。
演示:
8個->9個,length從16->32
9個->10個,length從32->64
10個->11個,length已經達到64,table[index]就從Node型別轉為TreeNode型別,說明樹化。
MIN_TREEIFY_CAPACITY:最小樹化容量64
10.什麼時候從樹-->連結串列?
當你刪除結點時,這棵樹的結點個數少於6個,會反序列化,變為連結串列。
UNTREEIFY_THRESHOLD:6
樹的結構太複雜,當結點少了以後,就用連結串列更好。
11.hashCode()和equals()方法的關係?
java中規定兩個相同(equals()為true)的物件必須具有相等的hashCode。
因為如果equals()為true而兩個物件的hashcode不同;那在整個儲存過程中就發生了悖論。
11.HashMap與HashTable的區別?
1.HashMap:執行緒不安全,效率高。允許key或value為null.
2.HashTable:執行緒安全,效率低。不允許key或value為null.
本文來自部落格園,作者:jsqup,轉載請註明原文連結:https://www.cnblogs.com/jsqup/p/15860192.html