57hashmap8 和hashmap7之間區別以及擴容解決死循環的問題

jdk1.8 核心參數:

HashMap 初始容量

/**
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

hashMap 最大容量

/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;

hashmap加載因子 提前擴容

/**
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;

鏈表長度大于8的時候,將鏈表轉為紅黑數

/**
 * 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.
 */
static final int TREEIFY_THRESHOLD = 8;

紅黑樹長度小于6的時候轉換為鏈表

/**
 * The bin count threshold for untreeifying a (split) bin during a
 * resize operation. Should be less than TREEIFY_THRESHOLD, and at
 * most 6 to mesh with shrinkage detection under removal.
 */
static final int UNTREEIFY_THRESHOLD = 6;

(數組容量>=64&鏈表長度大于8)鏈表轉紅黑樹

/**
 * The smallest table capacity for which bins may be treeified.
 * (Otherwise the table is resized if too many nodes in a bin.)
 * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
 * between resizing and treeification thresholds.
 */
static final int MIN_TREEIFY_CAPACITY = 64;

底層采用單向鏈表

/**
* Basic hash bin node, used for most entries. (See below for
* TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
*/

  final int hash;
    final K key;
    V value;
    Node<K,V> next;

將key的hash 保存起來是為了下次擴容的時候能夠計算該key在新的table中index的值。

table數組 類型: 單向鏈表

/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;

/**
* The number of key-value mappings contained in this map.
*/
transient int size;

transient  不能被序列化

遍歷hashmap集合的時候防止被篡改

/**
 * 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).
 */
transient int modCount;

加載因子

/**
 * The load factor for the hash table.
 *
 * @serial
 */
final float loadFactor;

hashmap put 方法底層實現;

n=table數組的長度 index=key 存放在那個index下標位置。tab 和p臨時table大小接收。

  1. Node<K,V>[] tab; Node<K,V> p; int n, i;

2,將全局table=tab 判斷是否為空,如果為空的情況下或者長度為0 開始對table實現擴容。
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;//懶加載默認擴容大小為16

3,計算key index的值判斷是否有發生index沖突,如果沒有發生index沖突
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);

獲取原來的table長度為0;
int oldCap = (oldTab == null) ? 0 : oldTab.length;

0 hashmap 下一次提前擴容的大小

int oldThr = threshold;

記錄新的table容量,新下一次擴容的大小。

int newCap, newThr = 0;

存放index下標的位置

4, tab[i] = newNode(hash, key, value, null);
5,##如果hash值相同且equals也相同就覆蓋值
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;

將新的value覆蓋給老的value

if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}

遍歷鏈表,如果鏈表為空的情況下,直接追加在next后面。

for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//如果鏈表長度大于8且長度>64直接轉為紅黑樹
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//查找鏈表中是否包含key如果存在key直接修改value
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}

modcount++ HashMap結果集 集合線程不安全
A 線程 遍歷 hashmap結果集 B線程向hashMap 存放key
modCount 新增++fastclass機制
java.util.HashMap 不是線程安全的,因此如果在使用迭代器的過程中有其他線程修改了map,那么將拋出ConcurrentModificationException,這就是所謂fail-fast策略。這一策略在源碼中的實現是通過 modCount 域,modCount 顧名思義就是修改次數,對HashMap 內容的修改都將增加這個值,那么在迭代器初始化過程中會將這個值賦給迭代器的 expectedModCount。在迭代過程中,判斷 modCount 跟 expectedModCount 是否相等,如果不相等就表示已經有其他線程修改了 Map:


package com.taotao.hashmap001;

import java.util.HashMap;

/**
 *@author tom
 *Date  2020/9/24 0024 8:09
 *
 */
public class Test11 {
    public static void main(String[] args) {
        HashMap<Object,String> hashmap=new HashMap<>();
        for (int i = 0; i < 12; i++) {
            hashmap.put(i,i+"");
        }
        hashmap.forEach((k,v)->{
            hashmap.put(13,13+"");
            System.out.println(k+","+v);
        });
    }
}


api\1.7.30\slf4j-api-1.7.30.jar" com.taotao.hashmap001.Test11
0,0
Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap.forEach(HashMap.java:1291)
    at com.taotao.hashmap001.Test11.main(Test11.java:16)

Process finished with exit code 1


遍歷hashmap的時候改變了hashmap 的長度 所以 報錯 modCount


public void forEach(BiConsumer<? super K, ? super V> action) {
        Node<K,V>[] tab;
        if (action == null)
            throw new NullPointerException();
        if (size > 0 && (tab = table) != null) {
            int mc = modCount;
            for (int i = 0; i < tab.length; ++i) {
                for (Node<K,V> e = tab[i]; e != null; e = e.next)
                    action.accept(e.key, e.value);
            }
            if (modCount != mc)
                throw new ConcurrentModificationException();
        }
    }

擴容:
HashMap7擴容產生死循環問題


oid transfer(Entry[] newTable, boolean rehash) {
  int newCapacity = newTable.length;
  for (Entry<K,V> e : table) {
      while(null != e) {
          Entry<K,V> next = e.next;
          if (rehash) {
              e.hash = null == e.key ? 0 : hash(e.key);
          }
          int i = indexFor(e.hash, newCapacity);
          e.next = newTable[i];
          newTable[i] = e;
          e = next;
      }
  }
}

HashMap1.7 擴容 16*2=32
hashmap1.8 擴容 16<<1 位移

擴容的時候原來的tablekey 轉移到新的table 數組中
重新計算時候 has 值不變 node節點中保存計算好hash值。只是改變下標
誤區:沒有重新計算hash值

異或運算^無符號右移>>>&與運算
1.<<(向左位移) 針對二進制,轉換成二進制后向左移動2位,后面用0補齊
10的二進制1010
0000 0000 0000 0000 0000 0000 0000 1010 ---32位
0000 0000 0000 0000 0000 0000 0010 1000
System.out.println(10 << 2);//1010 =40
2.>>(向右位移) 針對二進制,轉換成二進制后向右移動2位,操作數移除右邊界的位被屏蔽 正數高位
補0 負數補1
10的二進制1010
0000 0000 0000 0000 0000 0000 0000 1010
System.out.println(10 >> 2);//10=2
3.>>>(不帶符號右移) 針對二進制,轉換成二進制后向右移動2位,操作數移除右邊界的位被屏蔽
正數高位 補0 負數補0

異或運算^ 針對二進制,相同的為0,不同的為1
0010 --2
0011 --3
0001 --1
4.&(與運算) 針對二進制,00的0 11的1 10 的0
0010--2
0011--3
0010--2

HashMap如何降低Hash沖突概率

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
((p = tab[i = (n - 1) & hash])

1、保證不會發生數組越界
首先我們要知道的是,在HashMap,數組的長度按規定一定是2的冪。因此,數組的長度的二進制形式是:10000…000, 1后面有偶數個0。 那么,length - 1 的二進制形式就是01111.111, 0后面有偶數個1。最高位是0, 和hash值相“與”,結果值一定不會比數組的長度值大,因此也就不會發生數組越界。一個哈希值是8,二進制是1000,一個哈希值是9,二進制是1001。和1111“與”運算后,結果分別是1000和1001,它們被分配在了數組的不同位置,這樣,哈希的分布非常均勻。

HashMap8擴容底層原理

將原來的鏈表拆分兩個鏈表存放; 低位還是存放原來index位置 高位存放index=j+原來長度
if ((e.hash & oldCap) == 0) { 由于oldCap原來的容量沒有減去1 所以所有的hash&oldCap
為0或者1;

HashMap加載因子為什么是0.75而不是1或者0.5
產生背景:減少Hash沖突index的概率;
查詢效率與空間問題;

簡單推斷的情況下,提前做擴容:
1.如果加載因子越大,空間利用率比較高,有可能沖突概率越大;
2.如果加載因子越小,有可能沖突概率比較小,空間利用率不高;
空間和時間上平衡點:0.75
統計學概率:泊松分布是統計學和概率學常見的離散概率分布

HashMap如何存放1萬條key效率最高

image.png

(需要存儲的元素個數 / 負載因子) + 1
10000/0.75+1=13334

正常如果存放1萬個key的情況下 大概擴容10次=16384

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。