public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
/** * The default initial capacity - MUST be a power of two. */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/** * The next size value at which to resize (capacity * load factor). * @serial */ // If table == EMPTY_TABLE then this is the initial capacity at which the // table will be created when inflated. int threshold;
/** * The load factor used when none specified in constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f;
/** * The number of key-value mappings contained in this map. */ transient int size;
transient int modCount;
static final Entry<?,?>[] EMPTY_TABLE = {}; /** * The table, resized as necessary. Length MUST Always be a power of two. * 這裏也強調擴容時,長度必須是2的指數次冪 */ transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; int hash; }
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(); }
public V put(K key, V value) { // 1 若是table爲空則須要初始化 if (table == EMPTY_TABLE) { inflateTable(threshold); } // 2 若是key爲空,則單獨處理 if (key == null) return putForNullKey(value); // 3 根據key獲取hash值 int hash = hash(key); // 4 根據hash值和長度求取索引值。 int i = indexFor(hash, table.length); // 5 根據索引值獲取數組下的鏈表進行遍歷,判斷元素是否存在相同的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; } } // 6 若是不存在重複的key, 則須要建立新的Entry,而後添加至鏈表中。 // 先將修改次數加一 modCount++; addEntry(hash, key, value, i); return null; }
private void inflateTable(int toSize) { // Find a power of 2 >= toSize int capacity = roundUpToPowerOf2(toSize); // 其中閾值=容量*加載因子,而後再初始化數組。 threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1); table = new Entry[capacity]; initHashSeedAsNeeded(capacity); }
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; }
private V putForNullKey(V value) { // 取數組下標爲0的鏈表 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++; // 注意:索引值依然指定是0 addEntry(0, null, value, 0); return null; }
final int hash(Object k) { int h = hashSeed; if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } 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); }
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])) { // 進行2倍擴容 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++; }
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 = 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) { // 定一個next 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; } } }
經過上面分析,其實put函數仍是簡單的,不是很繞。那麼能從其中找到開頭的第二和第三個問題的答案嗎?下面總結下順便回答下這兩個問題:javascript
public V get(Object key) { if (key == null) return getForNullKey(); Entry<K,V> entry = getEntry(key); return null == entry ? null : entry.getValue(); }
第一步:若是key爲空,則直接從table[0]所對應的鏈表中查找(應該還記得put的時候爲null的key放在哪)。java
private V getForNullKey() { if (size == 0) { return null; } for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; }
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; }
Entry<K,V> next = e.next;
// 同理落位到2 int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; // 指向a newTable[i] = e; e = next;
e.next = newTable[i];