HashMap和Hashtable的底層實現都是數組+鏈表結構實現的,這點上完全一致
添加、刪除、獲取元素時都是先計算hash,根據hash和table.length計算index也就是table數組的下標,然后進行相應操作,下面以HashMap為例說明下它的簡單實現
/**
* HashMap的默認初始容量 必須為2的n次冪
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
/**
* HashMap的最大容量,可以認為是int的最大值
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 默認的加載因子
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* HashMap用來存儲數據的數組
*/
transient Entry[] table;
- HashMap的創建
HashMap默認初始化時會創建一個默認容量為16的Entry數組,默認加載因子為0.75,同時設置臨界值為16*0.75/** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); table = new Entry[DEFAULT_INITIAL_CAPACITY]; init(); } - put方法
HashMap會對null值key進行特殊處理,總是放到table[0]位置
put過程是先計算hash然后通過hash與table.length取摸計算index值,然后將key放到table[index]位置,當table[index]已存在其它元素時,會在table[index]位置形成一個鏈表,將新添加的元素放在table[index],原來的元素通過Entry的next進行鏈接,這樣以鏈表形式解決hash沖突問題,當元素數量達到臨界值(capactiy*factor)時,則進行擴容,是table數組長度變為table.length*2 -
public V put(K key, V value) { if (key == null) return putForNullKey(value); //處理null值 int hash = hash(key.hashCode());//計算hash int i = indexFor(hash, table.length);//計算在數組中的存儲位置 //遍歷table[i]位置的鏈表,查找相同的key,若找到則使用新的value替換掉原來的oldValue並返回oldValue 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; } } //若沒有在table[i]位置找到相同的key,則添加key到table[i]位置,新的元素總是在table[i]位置的第一個元素,原來的元素后移 modCount++; addEntry(hash, key, value, i); return null; } void addEntry(int hash, K key, V value, int bucketIndex) { //添加key到table[bucketIndex]位置,新的元素總是在table[bucketIndex]的第一個元素,原來的元素后移 Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); //判斷元素個數是否達到了臨界值,若已達到臨界值則擴容,table長度翻倍 if (size++ >= threshold) resize(2 * table.length); } - get方法
同樣當key為null時會進行特殊處理,在table[0]的鏈表上查找key為null的元素
get的過程是先計算hash然后通過hash與table.length取摸計算index值,然后遍歷table[index]上的鏈表,直到找到key,然后返回public V get(Object key) { if (key == null) return getForNullKey();//處理null值 int hash = hash(key.hashCode());//計算hash //在table[index]遍歷查找key,若找到則返回value,找不到返回null 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; } - remove方法
remove方法和put get類似,計算hash,計算index,然后遍歷查找,將找到的元素從table[index]鏈表移除public V remove(Object key) { Entry<K,V> e = removeEntryForKey(key); return (e == null ? null : e.value); } final Entry<K,V> removeEntryForKey(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); 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; 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; } - resize方法
resize方法在hashmap中並沒有公開,這個方法實現了非常重要的hashmap擴容,具體過程為:先創建一個容量為table.length*2的新table,修改臨界值,然后把table里面元素計算hash值並使用hash與table.length*2重新計算index放入到新的table里面
這里需要注意下是用每個元素的hash全部重新計算index,而不是簡單的把原table對應index位置元素簡單的移動到新table對應位置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); table = newTable; threshold = (int)(newCapacity * loadFactor); } void transfer(Entry[] newTable) { Entry[] src = table; int newCapacity = newTable.length; for (int j = 0; j < src.length; j++) { Entry<K,V> e = src[j]; if (e != null) { src[j] = null; do { Entry<K,V> next = e.next;
//重新對每個元素計算index int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } } - clear()方法
clear方法非常簡單,就是遍歷table然后把每個位置置為null,同時修改元素個數為0
需要注意的是clear方法只會清楚里面的元素,並不會重置capactiypublic void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; } - containsKey和containsValue
containsKey方法是先計算hash然后使用hash和table.length取摸得到index值,遍歷table[index]元素查找是否包含key相同的值public boolean containsKey(Object key) { return getEntry(key) != null; } final Entry<K,V> getEntry(Object key) { int hash = (key == null) ? 0 : hash(key.hashCode()); 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; }containsValue方法就比較粗暴了,就是直接遍歷所有元素直到找到value,由此可見HashMap的containsValue方法本質上和普通數組和list的contains方法沒什么區別,你別指望它會像containsKey那么高效
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; } - hash和indexFor
indexFor中的h & (length-1)就相當於h%length,用於計算index也就是在table數組中的下標
hash方法是對hashcode進行二次散列,以獲得更好的散列值
為了更好理解這里我們可以把這兩個方法簡化為 int index= key.hashCode()/table.length,以put中的方法為例可以這樣替換int hash = hash(key.hashCode());//計算hash int i = indexFor(hash, table.length);//計算在數組中的存儲位置 //上面這兩行可以這樣簡化 int i = key.key.hashCode()%table.length;
-
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); } static int indexFor(int h, int length) { return h & (length-1); }
