HashMap.put()和get()原理
阿新 • • 發佈:2019-01-10
/** * Returns the value to which the specified key is mapped, * or if this map contains no mapping for the key. * * 獲取key對應的value */ public V get(Object key) { if (key == null) return getForNullKey(); //獲取key的hash值 int hash = hash(key.hashCode()); // 在“該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.equals(k))) return e.value; } return null; } /** * Offloaded version of get() to look up null keys. Null keys map * to index 0. * 獲取key為null的鍵值對,HashMap將此鍵值對儲存到table[0]的位置*/ private V getForNullKey() { for (Entry<K,V> e = table[0]; e != null; e = e.next) { if (e.key == null) return e.value; } return null; } /** * Returns <tt>true</tt> if this map contains a mapping for the * specified key. * * HashMap是否包含key*/ public boolean containsKey(Object key) { return getEntry(key) != null; } /** * Returns the entry associated with the specified key in the * HashMap. * 返回鍵為key的鍵值對 */ final Entry<K,V> getEntry(Object key) { //先獲取雜湊值。如果key為null,hash = 0;這是因為key為null的鍵值對儲存在table[0]的位置。 int hash = (key == null) ? 0 : hash(key.hashCode()); //在該雜湊值對應的連結串列上查詢鍵值與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; } /** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for the key, the old * value is replaced. * * 將“key-value”新增到HashMap中,如果hashMap中包含了key,那麼原來的值將會被新值取代 */ public V put(K key, V value) { //如果key是null,那麼呼叫putForNullKey(),將該鍵值對新增到table[0]中 if (key == null) return putForNullKey(value); //如果key不為null,則計算key的雜湊值,然後將其新增到雜湊值對應的連結串列中 int hash = hash(key.hashCode()); int i = indexFor(hash, table.length); for (Entry<K,V> e = table[i]; e != null; e = e.next) { Object k; //如果這個key對應的鍵值對已經存在,就用新的value代替老的value。 if (e.hash == hash && ((k = e.key) == key || key.equals(k))) { V oldValue = e.value; e.value = value; e.recordAccess(this); return oldValue; } } modCount++; addEntry(hash, key, value, i); return null; }