HashMap歸檔-超越昨天的自己系列,hashmap歸檔
java HashMap
讀一下源碼,一個數組儲存資料:
transient Entry[] table;
內部存key和value的內部類:
static class Entry<K,V> implements Map.Entry<K,V> { final K key; V value; Entry<K,V> next; final int hash; /** * Creates new entry. */ Entry( int h, K k, V v, Entry<K,V> n) { value = v; next = n; key = k; hash = h; } public final K getKey() { return key; } public final V getValue() { return value; } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } 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 ( key== null ? 0 : key.hashCode()) ^ ( value== null ? 0 : value.hashCode()); } 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) { } }
所以HashMap的資料結構為數組下的鏈表結構,
public V put(K key, V value) { if (key == null) return putForNullKey(value); int hash = hash(key.hashCode()); int i = indexFor(hash, table.length);//hash 找到數組中位置 //遍曆鏈表 找出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++; //沒有key相同的 在數組的這個位置裡新加一個值進去 addEntry(hash, key, value, i); return null; }
放資料的代碼可以看出,從效能的角度來說,鏈表的長度越長,尋找一個key是否在這個map中的時間就越長。而在是否同一個鏈表上的key是由key.hashCode()決定的。
還注意到放null為key的對象時,是直接放入數組的頭部的。這樣處理也是最好的實現了吧。否則一個null還要找一遍。
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; }當在鏈表中加入新資料時,需要檢查是否需要resize,條件是已經佔用數組的長度是否已經達到數組當時的length*loadFactor(0.75),也就是說數組被使用到百分之75時就需要擴容啦。resize意味著數組擴容一倍,如此需要將現有的entry全部重新在這個擴容後的數組中重新hash到新的位置上,想象下元素很多的情況,必然影響效能。
void addEntry (int hash, K key, V value, int bucketIndex) { Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); if (size++ >= threshold) resize(2 * table. length); }
HashMap的hash演算法:
static int hash(int h) { // 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); } /** * Returns index for hash code h. */ static int indexFor(int h, int length) { return h & (length-1); }
這個要詳細看一下,hash方法中的演算法在以前文章中有記錄,可以參看:http://www.cnblogs.com/killbug/p/4560000.html
為了儘可能的試put的資料能平均的分布在數組上,提高map效能,上面的兩個方法就是來做這件事的。
hash方法將key.hashcode再進行了一次hash,hash函數的通過若干次的移位、異或操作,把hashcode的“1位”變得“鬆散”,在接下來和數組長度的於操作時可以得出更平均的數組下標。
我們注意到數組的length被要求是2的冪次方,如此在做與操作的時候減1就變成1111這種,如此是最好的。
看,左邊兩組是數組長度為16(2的4次方),右邊兩組是數組長度為15。兩組的hashcode均為8和9,但是很明顯,當它們和1110“與”的時候,產生了相同的結果,也就是說它們會定位到數組中的同一個位置上去,這就產生了碰撞,8和9會被放到同一個鏈表上,那麼查詢的時候就需要遍曆這個鏈表,得到8或者9,這樣就降低了查詢的效率。同時,我們也可以發現,當數組長度為15的時候,hashcode的值會與14(1110)進行“與”,那麼最後一位永遠是0,而0001,0011,0101,1001,1011,0111,1101這幾個位置永遠都不能存放元素了,空間浪費相當大,更糟的是這種情況中,數組可以使用的位置比數組長度小了很多,這意味著進一步增加了碰撞的幾率,減慢了查詢的效率!
public HashSet() { map = new HashMap<E,Object>(); }
比如 contains函數:
public boolean contains(Object o) { return map.containsKey(o); }
LinkedHashMap也經常使用,它整合HashMap,結構和HashMap一樣,為了實現順序訪問,在放元素(Entry)時,記錄順序。
Entry內部類也繼承HashMap的,然後自己加了before,after來記錄順序:
/** * LinkedHashMap entry. */ private static class Entry<K,V> extends HashMap.Entry<K,V> { // These fields comprise the doubly linked list used for iteration. Entry<K,V> before, after; Entry(int hash, K key, V value, HashMap.Entry<K,V> next) { super(hash, key, value, next); } /** * Removes this entry from the linked list. */ private void remove() { before.after = after; after.before = before; } /** * Inserts this entry before the specified existing entry in the list. */ private void addBefore(Entry<K,V> existingEntry) { after = existingEntry; before = existingEntry.before; before.after = this; after.before = this; } /** * This method is invoked by the superclass whenever the value * of a pre-existing entry is read by Map.get or modified by Map.set. * If the enclosing Map is access-ordered, it moves the entry * to the end of the list; otherwise, it does nothing. */ void recordAccess(HashMap<K,V> m) { LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m; if (lm.accessOrder) { lm.modCount++; remove(); addBefore(lm.header); } } void recordRemoval(HashMap<K,V> m) { remove(); } }
在前面put函數代碼裡我們看到是調用addEntry方法,而LinkedHashMap也就是重寫了這個方法,如此就調用到addBefore(header),即可每次加入元素都記錄了循序關聯性:
void addEntry(int hash, K key, V value, int bucketIndex) { createEntry(hash, key, value, bucketIndex); // Remove eldest entry if instructed, else grow capacity if appropriate Entry<K,V> eldest = header.after; if (removeEldestEntry(eldest)) { removeEntryForKey(eldest.key); } else { if (size >= threshold) resize(2 * table.length); } } /** * This override differs from addEntry in that it doesn't resize the * table or remove the eldest entry. */ void createEntry(int hash, K key, V value, int bucketIndex) { HashMap.Entry<K,V> old = table[bucketIndex]; Entry<K,V> e = new Entry<K,V>(hash, key, value, old); table[bucketIndex] = e; e.addBefore(header); size++; }
注意到一個細節,containsValue方法在HashMap中是需要遍曆數組的:
public boolean containsValue(Object value) { if (value == null) return containsNullValue(); Entry[] tab = 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; }
而在LinkedHashMap裡則不需要,因為我們維護了包含全部元素的鏈表,這個鏈表的長度肯定是小於數組長度的百分之75的,如果要尋找一個值是否在這裡面,遍曆這個鏈表就好了:
public boolean containsValue(Object value) { // Overridden to take advantage of faster iterator if (value==null) { for (Entry e = header.after; e != header; e = e.after) if (e.value==null) return true; } else { for (Entry e = header.after; e != header; e = e.after) if (value.equals(e.value)) return true; } return false; }