概要
- 類繼承關係
java.lang.Object
java.util.AbstractMap<K,V>
java.util.HashMap<K,V>
- 定義
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
- 要點
1) 與 Hashtable 區別在於:非同步,允許 null
2) 不保證次序,甚至不保證次序隨時間不變
3) 基本操作 put, get 常量時間
4) 遍歷操作 與 capacity+size 成正比
5) HashMap 性能與 capacity
和 load
factor
相關,load factor
是當前元素個數與capacity
的比值,通常設定爲 0.75
,如果此值過大,空間利用率高,但是衝突的可能性增加,因而可能導致查找時間增加,如果過小,反之。當元素個數大於 capacity
* load_factor
時,HashMap
會重新安排 Hash 表。因此高效地使用 HashMap
需要預估元素個數,設置最佳的 capacity
和 load
factor
,使得重新安排 Hash 表的次數下降。
實現
- capacity
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);
// Find a power of 2 >= initialCapacity
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
this.loadFactor = loadFactor;
threshold = (int)Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
init();
}
注意,HashMap
並不會按照你指定的 initialCapacity
來確定 capacity
大小,而是會找到一個比它大的數,並且是 2的n次方
。
爲什麼要是 2 的n次方呢?
- hash
/**
* Retrieve object hash code and applies a supplemental hash function to the
* result hash, which defends against poor quality hash functions. This is
* critical because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
final int hash(Object k) {
int h = 0;
if (useAltHashing) {
if (k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h = 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);
}
如果 k
是 String
類型,使用了特別的 hash
函數,否則首先得到 hashCode
,然後又對 h
作了移位,異或操作,問題:
爲什麼這裏要作移位,異或操作呢?
at 22:
h = abcdefgh
h1 = h >>> 20 = 00000abc
h2 = h >>> 12 = 000abcde
h3 = h1 ^ h2 = [0][0][0][a][b][a^c][b^d][c^e]
h4 = h ^ h3 = [a][b][c][a^d][b^e][a^c^f][b^d^g][c^e^h]
h5 = h4 >>> 4 = [0][a][b][c][a^d][b^e][a^c^f][b^d^g]
h6 = h4 >>> 7 = ([0][:3])[0][0][a][b][c][a^d][b^e][a^c^f]([a^c^f][0])
h7 = h4 ^ h6 = 太兇殘了。。。
- put
/**
* 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.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
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++;
addEntry(hash, key, value, i);
return null;
}
從 put
其實可以看出各個 hash
表是如何實現的,首先取得 hash
值,然後由 indexFor
找到鏈表頭的 index
,然後開始遍歷鏈表,如果鏈表裏的一個元素 hash
值與當前 key
的 hash
值相同,或者元素 key
的引用與當前 key
相同,或者 equals
相同,就說明當前 key
已經在 hash
表裏了,那麼修改它的值,返回舊值。
如果不在表裏,會調用 addEntry
,將這一 (key,
value)
對添加進去。
/**
* Adds a new entry with the specified key, value and hash code to
* the specified bucket. It is the responsibility of this
* method to resize the table if appropriate.
*
* Subclass overrides this to alter the behavior of put method.
*/
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);
}
/**
* Like addEntry except that this version is used when creating entries
* as part of Map construction or "pseudo-construction" (cloning,
* deserialization). This version needn't worry about resizing the table.
*
* Subclass overrides this to alter the behavior of HashMap(Map),
* clone, and readObject.
*/
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++;
}
可以看出,新增加元素時,可能會調整 hash
表的大小,原因之前已經討論過。直接的添加在 createEntry
中完成,但是這裏並沒有體現出如何處理衝突。
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
注意這裏,將 n
賦值給了 next
,這其實就是將新添加的項指向了當前鏈表頭。這一操作在 Entry
的構造函數中完成。
put
操作的基本思路在到這裏已經很清楚了,有了這個思路,不難想象 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) {
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;
}
和 put
差不多,只是找到了就會返回相應的 value
,找不到就返回 null
。
如果對代碼有更多見解,可以在這個頁面添加註釋: rtfcode-HashMap