java - hashmap put方法問題
問題描述
public V put(K key, V value) {if (key == null) return putForNullKey(value);int hash = hash(key);int i = indexFor(hash, table.length);for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {V oldValue = e.value;e.value = value;e.recordAccess(this);return oldValue; }}modCount++;addEntry(hash, key, value, i);return null; }
void addEntry(int hash, K key, V value, int bucketIndex) { if ((size >= threshold) && (null != table[bucketIndex])) {resize(2 * table.length);hash = (null != key) ? hash(key) : 0;bucketIndex = indexFor(hash, table.length); } createEntry(hash, key, value, bucketIndex);}
void createEntry(int hash, K key, V value, int bucketIndex) {Entry<K,V> e = table[bucketIndex];table[bucketIndex] = new Entry<>(hash, key, value, e);size++; }
如果put 鍵索引相同key不同的元素,addEntry()怎么保存元素到鏈表尾部,createEntry()方法?
問題解答
回答1:看這段源碼
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 keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null) e.value = value;afterNodeAccess(e);return oldValue; }}++modCount;if (++size > threshold) resize();afterNodeInsertion(evict);return null; }
如果相同key,不同value會(huì)進(jìn)入這段:
if (e != null) { // existing mapping for keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null) e.value = value;afterNodeAccess(e);return oldValue; }
相關(guān)文章:
1. javascript - vscode alt+shift+f 格式化js代碼,通不過eslint的代碼風(fēng)格檢查怎么辦。。。2. javascript - 如何將一個(gè)div始終固定在某個(gè)位置;無論屏幕和分辨率怎么變化;div位置始終不變3. html5 - 有可以一次性把所有 css外部樣式轉(zhuǎn)為html標(biāo)簽內(nèi)style=" "的方法嗎?4. javascript - 有什么比較好的網(wǎng)頁版shell前端組件?5. java - 如何寫一個(gè)intellij-idea插件,實(shí)現(xiàn)編譯時(shí)修改源代碼的目的6. javascript - 原生canvas中如何獲取到觸摸事件的canvas內(nèi)坐標(biāo)?7. java 中Long 類型如何轉(zhuǎn)換成Double?8. javascript - 求解答:實(shí)例對(duì)象調(diào)用constructor,此時(shí)constructor內(nèi)的this的指向?9. html - vue項(xiàng)目中用到了elementUI問題10. javascript - [js]為什么畫布里不出現(xiàn)圖片呢?在線等
