以下內容基於jdk1.7.0_79源碼; 基於哈希表的一個Map介面實現,存儲的對象是一個鍵值對對象(Entry<K,V>); 基於數組和鏈表實現,內部維護著一個數組table,該數組保存著每個鏈表的表頭結點;查找時,先通過hash函數計算hash值,再根據hash值計算數組索引,然後根據索引找到鏈
以下內容基於jdk1.7.0_79源碼;
什麼是HashMap
基於哈希表的一個Map介面實現,存儲的對象是一個鍵值對對象(Entry<K,V>);
HashMap補充說明
基於數組和鏈表實現,內部維護著一個數組table,該數組保存著每個鏈表的表頭結點;查找時,先通過hash函數計算hash值,再根據hash值計算數組索引,然後根據索引找到鏈表表頭結點,然後遍歷查找該鏈表;
HashMap數據結構
畫了個示意圖,如下,左邊的數組索引是根據hash值計算得到,不同hash值有可能產生一樣的索引,即哈希衝突,此時採用鏈地址法處理哈希衝突,即將所有索引一致的節點構成一個單鏈表;
HashMap繼承的類與實現的介面
Map介面,方法的含義很簡單,基本上看個方法名就知道了,後面會在HashMap源碼分析里詳細說明
AbstractMap抽象類中定義的方法
HashMap源碼分析,大部分都加了註釋
package java.util; import java.io.*; public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { /** * 預設初始容量,預設為2的4次方 = 16 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * 最大容量,預設為2的30次方 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 預設負載因數,預設為0.75 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** *當數組表還沒擴容的時候,一個共用的空表對象 */ static final Entry<?,?>[] EMPTY_TABLE = {}; /** * 數組表,大小可以改變,且大小必須為2的冪 */ transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; /** * 當前Map中key-value映射的個數 */ transient int size; /** * 下次擴容閾值,當size > capacity * load factor時,開始擴容 */ int threshold; /** * 負載因數 */ final float loadFactor; /** * Hash表結構性修改次數,用於實現迭代器快速失敗行為 */ transient int modCount; /** * 容量閾值,預設大小為Integer.MAX_VALUE */ static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE; /** * 靜態內部類Holder,存放一些只能在虛擬機啟動後才能初始化的值 */ private static class Holder { /** * 容量閾值,初始化hashSeed的時候會用到該值 */ static final int ALTERNATIVE_HASHING_THRESHOLD; static { //獲取系統變數jdk.map.althashing.threshold String altThreshold = java.security.AccessController.doPrivileged( new sun.security.action.GetPropertyAction( "jdk.map.althashing.threshold")); int threshold; try { threshold = (null != altThreshold) ? Integer.parseInt(altThreshold) : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT; // jdk.map.althashing.threshold系統變數預設為-1,如果為-1,則將閾值設為Integer.MAX_VALUE if (threshold == -1) { threshold = Integer.MAX_VALUE; } //閾值需要為正數 if (threshold < 0) { throw new IllegalArgumentException("value must be positive integer."); } } catch(IllegalArgumentException failed) { throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed); } ALTERNATIVE_HASHING_THRESHOLD = threshold; } } /** * 計算hash值的時候需要用到 */ transient int hashSeed = 0; /** * 生成一個空的HashMap,並指定其容量大小和負載因數 * */ public HashMap(int initialCapacity, float loadFactor) { //保證初始容量大於等於0 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); //保證初始容量不大於最大容量MAXIMUM_CAPACITY if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; //loadFactor小於0或為無效數字 if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); //負載因數 this.loadFactor = loadFactor; //下次擴容大小 threshold = initialCapacity; init(); } /** * 生成一個空的HashMap,並指定其容量大小,負載因數使用預設的0.75 * */ public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * 生成一個空的HashMap,容量大小使用預設值16,負載因數使用預設值0.75 */ public HashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR); } /** * 根據指定的map生成一個新的HashMap,負載因數使用預設值,初始容量大小為Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,DEFAULT_INITIAL_CAPACITY) */ public HashMap(Map<? extends K, ? extends V> m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR); inflateTable(threshold); putAllForCreate(m); } //返回>=number的最小2的n次方值,如number=5,則返回8 private static int roundUpToPowerOf2(int number) { // assert number >= 0 : "number must be non-negative"; return number >= MAXIMUM_CAPACITY ? MAXIMUM_CAPACITY : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1; } /** * 對table擴容 */ private void inflateTable(int toSize) { // Find a power of 2 >= toSize //找一個值(2的n次方,且>=toSize) int capacity = roundUpToPowerOf2(toSize); //下次擴容閾值 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); table = new Entry[capacity]; initHashSeedAsNeeded(capacity); } // internal utilities void init() { } /** * 初始化hashSeed */ final boolean initHashSeedAsNeeded(int capacity) { boolean currentAltHashing = hashSeed != 0; boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD); boolean switching = currentAltHashing ^ useAltHashing; if (switching) { hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0; } return switching; } /** * 生成hash值 */ final int hash(Object k) { int h = hashSeed; //如果key是字元串,調用un.misc.Hashing.stringHash32生成hash值 //Oracle表示能生成更好的hash分佈,不過這在jdk8中已刪除 if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } //一次散列,調用k的hashCode方法,與hashSeed做異或操作 h ^= k.hashCode(); // This function ensures that hashCodes that differ only by // constant multiples at each bit position have a bounded // number of collisions (approximately 8 at default load factor). //二次散列, h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } /** * 返回hash值的索引,採用除模取餘法,h & (length-1)操作 等價於 hash % length操作, 但&操作性能更優 */ 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); } /** * 返回key-value映射個數 */ public int size() { return size; } /** * 判斷map是否為空 */ public boolean isEmpty() { return size == 0; } /** * 返回指定key對應的value */ public V get(Object key) { //key為null情況 if (key == null) return getForNullKey(); //根據key查找節點 Entry<K,V> entry = getEntry(key); //返回key對應的值 return null == entry ? null : entry.getValue(); } /** * 查找key為null的value,註意如果key為null,則其hash值為0,預設是放在table[0]里的 */ private V getForNullKey() { if (size == 0) { return null; } //在table[0]的鏈表上查找key為null的鍵值對,因為null預設是存在table[0]的桶里 for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; } /** *判斷是否包含指定的key */ public boolean containsKey(Object key) { return getEntry(key) != null; } /** * 根據key查找鍵值對,找不到返回null */ final Entry<K,V> getEntry(Object key) { if (size == 0) { return null; } //如果key為null,hash值為0,否則調用hash方法,對key生成hash值 int hash = (key == null) ? 0 : hash(key); //調用indexFor方法生成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; } /** * 向map存入一個鍵值對,如果key已存在,則覆蓋 */ public V put(K key, V value) { //數組為空,對數組擴容 if (table == EMPTY_TABLE) { inflateTable(threshold); } //對key為null的鍵值對調用putForNullKey處理 if (key == null) return putForNullKey(value); //生成hash值 int hash = hash(key); //生成hash值索引 int i = indexFor(hash, table.length); //查找是否有key“相等”的鍵值對,有的話覆蓋 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++; //在指定hash值索引處的鏈表上增加該鍵值對 addEntry(hash, key, value, i); return null; } /** * 存放key為null的鍵值對,存放在索引為0的鏈表上,已存在的話,替換 */ private V putForNullKey(V value) { for (Entry<K,V> e = table[0]; e != null; e = e.next) { //已存在key為null,則替換 if (e.key == null) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } //操作次數加一,用於迭代器快速失敗行為 modCount++; //在指定hash值索引處的鏈表上增加該鍵值對 addEntry(0, null, value, 0); return null; } /** * 添加鍵值對 */ private void putForCreate(K key, V value) { //生成hash值 int hash = null == key ? 0 : hash(key); //生成hash值索引, int i = indexFor(hash, table.length); /** * key“相等”,則替換 */ for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { e.value = value; return; } } //在指定索引處的鏈表上創建該鍵值對 createEntry(hash, key, value, i); } //將制定map的鍵值對添加到map中 private void putAllForCreate(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) putForCreate(e.getKey(), e.getValue()); } /** * 對數組擴容 */ void resize(int newCapacity) { Entry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return; } //創建一個指定大小的數組 Entry[] newTable = new Entry[newCapacity]; transfer(newTable, initHashSeedAsNeeded(newCapacity)); //table索引替換成新數組 table = newTable; //重新計算閾值 threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1); } /** * 拷貝舊的鍵值對到新的哈希表中 */ void 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]; //將e放到索引為i處 newTable[i] = e; //將e設置成下個節點 e = next; } } } /** * 將制定map的鍵值對put到本map,key“相等”的直接覆蓋 */ public void putAll(Map<? extends K, ? extends V> m) { int numKeysToBeAdded = m.size(); if (numKeysToBeAdded == 0) return; //空map,擴容 if (table == EMPTY_TABLE) { inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold)); } /* * 判斷是否需要擴容 */ if (numKeysToBeAdded > threshold) { int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1); if (targetCapacity > MAXIMUM_CAPACITY) targetCapacity = MAXIMUM_CAPACITY; int newCapacity = table.length; while (newCapacity < targetCapacity) newCapacity <<= 1; if (newCapacity > table.length) resize(newCapacity); } //依次遍歷鍵值對,並put for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) put(e.getKey(), e.getValue()); } /** * 移除指定key的鍵值對 */ public V remove(Object key) { Entry<K,V> e = removeEntryForKey(key); return (e == null ? null : e.value); } /** * 移除指定key的鍵值對 */ final Entry<K,V> removeEntryForKey(Object key) { if (size == 0) { return null; } //計算hash值及索引 int hash = (key == null) ? 0 : hash(key); int i = indexFor(hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> e = prev; //頭節點為table[i]的單鏈表上執行刪除節點操作 while (e != null) { Entry<K,V> next = e.next; Object k; //找到要刪除的節點 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; } /** * 刪除指定鍵值對對象(Entry對象) */ final Entry<K,V> removeMapping(Object o) { if (size == 0 || !(o instanceof Map.Entry)) return null; Map.Entry<K,V> entry = (Map.Entry<K,V>) o; Object key = entry.getKey(); int hash = (key == null) ? 0 : hash(key); //得到數組索引 int i = indexFor(hash, table.length); Entry<K,V> prev = table[i]; Entry<K,V> e = prev; //開始遍歷該單鏈表 while (e != null) { Entry<K,V> next = e.next; //找到節點 if (e.hash == hash && e.equals(entry)) { modCount++; size--; if (prev == e) table[i] = next; else prev.next = next; e.recordRemoval(this); return e; } prev = e; e = next; } return e; } /** * 清空map,將table數組所有元素設為null */ public void clear() { modCount++; Arrays.fill(table, null); size = 0; } /** * 判斷是否含有指定value的鍵值對 */ public boolean containsValue(Object value) { if (value == null) return containsNullValue(); Entry[] tab = table; //遍歷table數組 for (int i = 0; i < tab.length ; i++) //遍歷每條單鏈表 for (Entry e = tab[i] ; e != null ; e = e.next) if (value.equals(e.value)) return true; return false; } /** * 判斷是否含有value為null的鍵值對 */ private boolean containsNullValue() { Entry[] tab = table; for (int i = 0; i < tab.length ; i++) for (Entry e = tab[i] ; e != null ; e = e.next) if (e.value == null) return true; return false; } /** * 淺拷貝,鍵值對不複製 */ public Object clone() { HashMap<K,V> result = null; try { result = (HashMap<K,V>)super.clone(); } catch (CloneNotSupportedException e) { // assert false; } if (result.table != EMPTY_TABLE) { result.inflateTable(Math.min( (int) Math.min( size * Math.min(1 / loadFactor, 4.0f), // we have limits... HashMap.MAXIMUM_CAPACITY), table.length)); } result.entrySet = null; result.modCount = 0; result.size = 0; result.init(); result.putAllForCreate(this); return result; } //內部類,節點對象,每個節點包含下個節點的引用 static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; /** * 創建節點 */ Entry(int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } //獲取節點的key public final K getKey() { return key; } //獲取節點的value public final V getValue() { return value; } //設置新value,並返回舊的value public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } //判斷key和value是否相同,兩個都“相等”,返回true public final boolean equals(Object o) { if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Object k1 = getKey(); Object k2 = e.getKey(); if (k1 == k2 || (k1 != null && k1.equals(k2))) { Object v1 = getValue(); Object v2 = e.getValue(); if (v1 == v2 || (v1 != null && v1.equals(v2))) return true; } return false; } public final int hashCode() { return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue()); } public final String toString() { return getKey() + "=" + getValue(); } /** * This method is invoked whenever the value in an entry is * overwritten by an invocation of put(k,v) for a key k that's already * in the HashMap. */ void recordAccess(HashMap<K,V> m) { } /** * This method is invoked whenever the entry is * removed from the table. */ void recordRemoval(HashMap<K,V> m) { } } /** * 添加新節點,如有必要,執行擴容操作 */ 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++; } //hashmap迭代器 private abstract class HashIterator<E> implements Iterator<E> { Entry<K,V> next; // 下個鍵值對索引 int expectedModCount; // 用於判斷快速失敗行為 int index; // current slot Entry<K,V> current; // current entry HashIterator() { expectedModCount = modCount; if (size > 0) { // advance to first entry Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } } public final boolean hasNext() { return next != null; } final Entry<K,V> nextEntry() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); Entry<K,V> e = next; if (e == null) throw new NoSuchElementException(); if ((next = e.next) == null) { Entry[] t = table; while (index < t.length && (next = t[index++]) == null) ; } current = e; return e; } public void remove() { if (current == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); Object k = current.key; current = null; HashMap.this.removeEntryForKey(k); expectedModCount = modCount; } } //ValueIterator迭代器 private final class ValueIterator extends HashIterator<V> { public V next() { return nextEntry().value; } } //KeyIterator迭代器 private final class KeyIterator extends HashIterator<K> { public K next() { return nextEntry().getKey(); } } ////KeyIterator迭代器 private final class EntryIterator extends HashIterator<Map.Entry<K,V>> { public Map.Entry<K,V> next() { return nextEntry(); } } // 返回迭代器方法 Iterator<K> newKeyIterator() { return new KeyIterator(); } Iterator<V> newValueIterator() { return new ValueIterator(); } Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); } // Views private transient Set<Map.Entry<K,V>> entrySet = null;