java HashMap 原理 資料結構
阿新 • • 發佈:2018-12-28
//這是 map的容器 transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; //這是 Entry物件 ,可以看出 Entry是連結串列 static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; } 首先存物件 put(key,value); 裡面有一個這個方法 這個方法 需要兩個引數 ,hash值和length ,這個length實際上就是 table.length 根據 hash值和length計算出一個index,兩個不同的hash值計算出得到相同的index,就會記錄在 連結串列裡面 /** * Returns index for hash code h. */ static int indexFor(int h, int length) { // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2"; return h & (length-1); } 當table.length長度不夠,size是實際上table中非空元素的個數 size>threshold 臨界值的時候就會自動擴容,擴容會兩倍擴容,這是固定寫死的 擴容後會重新建立table,table裡面的元素index會 根據 table.length 和hash值 重新計算 threshold = table.length*loadFactor 這個比例預設是0.75 預設hashMap的容量是 16 static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 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); } hashMap的優點就是 插入和查詢速度都很快 結合了 陣列和連結串列的 儲存方式 可更改的引數 初始容量預設16 和 閥值比例 預設0.75