標籤:
定義
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
public abstract class AbstractMap<K,V> implements Map<K,V>
HashMap實現了Map介面,繼承AbstractMap。其中Map介面定義了鍵映射到值的規則,而AbstractMap類提供 Map 介面的骨幹實現,以最大限度地減少實現此介面所需的工作,其實AbstractMap類已經實現了Map。
資料結構
我們知道在Java中最常用的兩種結構是數組和指標引用。實際上HashMap是一個“鏈表散列”,如下是它資料結構:
從我們可以看出HashMap底層實現還是數組,只是數組的每一項都是一條鏈。其中參數initialCapacity就代表了該數組的長度。下面為HashMap建構函式的源碼://jdk7把有些過程方法put的時候去做了,在讀寫解析上會體現。
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; threshold = initialCapacity; init(); }
此段代碼做了一些變數賦值和參數初始化,早期JDK給table賦值也是在構造器中的,即每次建立一個HashMap時,都會初始化一個table數組。table數組的元素為Entry節點。。
讀寫實現
public V put(K key, V value) { //jdk新版本,建立數組的時機在這了 if (table == EMPTY_TABLE) { inflateTable(threshold); } //hashmap允許放key為NULL的資料 if (key == null) return putForNullKey(value); //計算此key的hash值 int hash = hash(key); //根據hash值找到此key在數組的中下標 int i = indexFor(hash, table.length); //遍曆此下標處的Entry鏈表 for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; //如果此key已存在則覆蓋 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; //添加新key到此下標中 addEntry(hash, key, value, i); return null; } private void inflateTable(int toSize) { int capacity = roundUpToPowerOf2(toSize); threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); //此處表名HashMap是數組加鏈表的結構儲存的 table = new Entry[capacity]; initHashSeedAsNeeded(capacity); } //key為NULL的值始終在數組下標0的位置 private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(0, null, value, 0); return null; } //計算hash值 final int hash(Object k) { int h = hashSeed; if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h ^= k.hashCode(); h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } //通過hash值計算此key在數組中的下標 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); } 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]; //把新加的放在原先在的前面,原先的是e,現在的是new,next指向e table[bucketIndex] = new Entry<>(hash, key, value, e);//假設現在是new size++; }
代碼中很多思想用到了數學裡的一些概念,為了效能最佳化資料分配平均和合理性的保證。譬如數組大小啥的,都用2的指數來玩,這方面不是很懂,就不獻醜了。
下面的get代碼比較好理解就不解釋了。
public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); } final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } int hash = (key == null) ? 0 : hash(key); for (Entry<K,V> e = table[indexFor(hash, table.length)]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } return null; }
HashMap源碼解析