hashmap實(shí)現(xiàn)原理淺析
看了下JAVA里面有HashMap、Hashtable、HashSet三種hash集合的實(shí)現(xiàn)源碼,這里總結(jié)下,理解錯(cuò)誤的地方還望指正
HashSet和HashMap、Hashtable的區(qū)別
HashMap和Hashtable的實(shí)現(xiàn)原理
HashMap的簡(jiǎn)化實(shí)現(xiàn)MyHashMap
HashMap和Hashtable的區(qū)別
- 兩者最主要的區(qū)別在于Hashtable是線程安全,而HashMap則非線程安全
Hashtable的實(shí)現(xiàn)方法里面都添加了synchronized關(guān)鍵字來確保線程同步,因此相對(duì)而言HashMap性能會(huì)高一些,我們平時(shí)使用時(shí)若無特殊需求建議使用HashMap,在多線程環(huán)境下若使用HashMap需要使用Collections.synchronizedMap()方法來獲取一個(gè)線程安全的集合(Collections.synchronizedMap()實(shí)現(xiàn)原理是Collections定義了一個(gè)SynchronizedMap的內(nèi)部類,這個(gè)類實(shí)現(xiàn)了Map接口,在調(diào)用方法時(shí)使用synchronized來保證線程同步,當(dāng)然了實(shí)際上操作的還是我們傳入的HashMap實(shí)例,簡(jiǎn)單的說就是Collections.synchronizedMap()方法幫我們?cè)诓僮鱄ashMap時(shí)自動(dòng)添加了synchronized來實(shí)現(xiàn)線程同步,類似的其它Collections.synchronizedXX方法也是類似原理) - HashMap可以使用null作為key,而Hashtable則不允許null作為key
雖說HashMap支持null值作為key,不過建議還是盡量避免這樣使用,因?yàn)橐坏┎恍⌒氖褂昧耍粢虼艘l(fā)一些問題,排查起來很是費(fèi)事
HashMap以null作為key時(shí),總是存儲(chǔ)在table數(shù)組的第一個(gè)節(jié)點(diǎn)上 - HashMap是對(duì)Map接口的實(shí)現(xiàn),HashTable實(shí)現(xiàn)了Map接口和Dictionary抽象類
- HashMap的初始容量為16,Hashtable初始容量為11,兩者的填充因子默認(rèn)都是0.75
HashMap擴(kuò)容時(shí)是當(dāng)前容量翻倍即:capacity*2,Hashtable擴(kuò)容時(shí)是容量翻倍+1即:capacity*2+1 - 兩者計(jì)算hash的方法不同
Hashtable計(jì)算hash是直接使用key的hashcode對(duì)table數(shù)組的長(zhǎng)度直接進(jìn)行取模
int hash = key.hashCode(); int index = (hash & 0x7FFFFFFF) % tab.length;
HashMap計(jì)算hash對(duì)key的hashcode進(jìn)行了二次hash,以獲得更好的散列值,然后對(duì)table數(shù)組長(zhǎng)度取摸
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); }
- HashMap和Hashtable的底層實(shí)現(xiàn)都是數(shù)組+鏈表結(jié)構(gòu)實(shí)現(xiàn)
HashSet和HashMap、Hashtable的區(qū)別
除開HashMap和Hashtable外,還有一個(gè)hash集合HashSet,有所區(qū)別的是HashSet不是key value結(jié)構(gòu),僅僅是存儲(chǔ)不重復(fù)的元素,相當(dāng)于簡(jiǎn)化版的HashMap,只是包含HashMap中的key而已
通過查看源碼也證實(shí)了這一點(diǎn),HashSet內(nèi)部就是使用HashMap實(shí)現(xiàn),只不過HashSet里面的HashMap所有的value都是同一個(gè)Object而已,因此HashSet也是非線程安全的,至于HashSet和Hashtable的區(qū)別,HashSet就是個(gè)簡(jiǎn)化的HashMap的,所以你懂的
下面是HashSet幾個(gè)主要方法的實(shí)現(xiàn)
private transient HashMap<E,Object> map;
private static final Object PRESENT = new Object(); public HashSet() { map = new HashMap<E,Object>(); } public boolean contains(Object o) { return map.containsKey(o); } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean remove(Object o) { return map.remove(o)==PRESENT; } public void clear() { map.clear(); }
HashMap和Hashtable的實(shí)現(xiàn)原理
HashMap和Hashtable的底層實(shí)現(xiàn)都是數(shù)組+鏈表結(jié)構(gòu)實(shí)現(xiàn)的,這點(diǎn)上完全一致
添加、刪除、獲取元素時(shí)都是先計(jì)算hash,根據(jù)hash和table.length計(jì)算index也就是table數(shù)組的下標(biāo),然后進(jìn)行相應(yīng)操作,下面以HashMap為例說明下它的簡(jiǎn)單實(shí)現(xiàn)
/** * HashMap的默認(rèn)初始容量 必須為2的n次冪 */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * HashMap的最大容量,可以認(rèn)為是int的最大值 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * 默認(rèn)的加載因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * HashMap用來存儲(chǔ)數(shù)據(jù)的數(shù)組 */ transient Entry[] table;
- HashMap的創(chuàng)建
HashMap默認(rèn)初始化時(shí)會(huì)創(chuàng)建一個(gè)默認(rèn)容量為16的Entry數(shù)組,默認(rèn)加載因子為0.75,同時(shí)設(shè)置臨界值為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會(huì)對(duì)null值key進(jìn)行特殊處理,總是放到table[0]位置
put過程是先計(jì)算hash然后通過hash與table.length取摸計(jì)算index值,然后將key放到table[index]位置,當(dāng)table[index]已存在其它元素時(shí),會(huì)在table[index]位置形成一個(gè)鏈表,將新添加的元素放在table[index],原來的元素通過Entry的next進(jìn)行鏈接,這樣以鏈表形式解決hash沖突問題,當(dāng)元素?cái)?shù)量達(dá)到臨界值(capactiy*factor)時(shí),則進(jìn)行擴(kuò)容,是table數(shù)組長(zhǎng)度變?yōu)閠able.length*2 -
public V put(K key, V value) { if (key == null) return putForNullKey(value); //處理null值 int hash = hash(key.hashCode());//計(jì)算hash int i = indexFor(hash, table.length);//計(jì)算在數(shù)組中的存儲(chǔ)位置 //遍歷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]位置的第一個(gè)元素,原來的元素后移 modCount++; addEntry(hash, key, value, i); return null; } void addEntry(int hash, K key, V value, int bucketIndex) { //添加key到table[bucketIndex]位置,新的元素總是在table[bucketIndex]的第一個(gè)元素,原來的元素后移 Entry<K,V> e = table[bucketIndex]; table[bucketIndex] = new Entry<K,V>(hash, key, value, e); //判斷元素個(gè)數(shù)是否達(dá)到了臨界值,若已達(dá)到臨界值則擴(kuò)容,table長(zhǎng)度翻倍 if (size++ >= threshold) resize(2 * table.length); }
- get方法
同樣當(dāng)key為null時(shí)會(huì)進(jìn)行特殊處理,在table[0]的鏈表上查找key為null的元素
get的過程是先計(jì)算hash然后通過hash與table.length取摸計(jì)算index值,然后遍歷table[index]上的鏈表,直到找到key,然后返回
public V get(Object key) { if (key == null) return getForNullKey();//處理null值 int hash = hash(key.hashCode());//計(jì)算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類似,計(jì)算hash,計(jì)算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中并沒有公開,這個(gè)方法實(shí)現(xiàn)了非常重要的hashmap擴(kuò)容,具體過程為:先創(chuàng)建一個(gè)容量為table.length*2的新table,修改臨界值,然后把table里面元素計(jì)算hash值并使用hash與table.length*2重新計(jì)算index放入到新的table里面
這里需要注意下是用每個(gè)元素的hash全部重新計(jì)算index,而不是簡(jiǎn)單的把原table對(duì)應(yīng)index位置元素簡(jiǎn)單的移動(dòng)到新table對(duì)應(yīng)位置
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;
//重新對(duì)每個(gè)元素計(jì)算index int i = indexFor(e.hash, newCapacity); e.next = newTable[i]; newTable[i] = e; e = next; } while (e != null); } } } - clear()方法
clear方法非常簡(jiǎn)單,就是遍歷table然后把每個(gè)位置置為null,同時(shí)修改元素個(gè)數(shù)為0
需要注意的是clear方法只會(huì)清楚里面的元素,并不會(huì)重置capactiy
public void clear() { modCount++; Entry[] tab = table; for (int i = 0; i < tab.length; i++) tab[i] = null; size = 0; }
- containsKey和containsValue
containsKey方法是先計(jì)算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方法本質(zhì)上和普通數(shù)組和list的contains方法沒什么區(qū)別,你別指望它會(huì)像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)就相當(dāng)于h%length,用于計(jì)算index也就是在table數(shù)組中的下標(biāo)
hash方法是對(duì)hashcode進(jìn)行二次散列,以獲得更好的散列值
為了更好理解這里我們可以把這兩個(gè)方法簡(jiǎn)化為 int index= key.hashCode()/table.length,以put中的方法為例可以這樣替換int hash = hash(key.hashCode());//計(jì)算hash int i = indexFor(hash, table.length);//計(jì)算在數(shù)組中的存儲(chǔ)位置 //上面這兩行可以這樣簡(jiǎn)化 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); }
HashMap的簡(jiǎn)化實(shí)現(xiàn)MyHashMap
為了加深理解,我個(gè)人實(shí)現(xiàn)了一個(gè)簡(jiǎn)化版本的HashMap,注意哦,僅僅是簡(jiǎn)化版的功能并不完善,僅供參考
package cn.lzrabbit.structure; /** * Created by rabbit on 14-5-4. */ public class MyHashMap { //默認(rèn)初始化大小 16 private static final int DEFAULT_INITIAL_CAPACITY = 16; //默認(rèn)負(fù)載因子 0.75 private static final float DEFAULT_LOAD_FACTOR = 0.75f; //臨界值 private int threshold; //元素個(gè)數(shù) private int size; //擴(kuò)容次數(shù) private int resize; private HashEntry[] table; public MyHashMap() { table = new HashEntry[DEFAULT_INITIAL_CAPACITY]; threshold = (int) (DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR); size = 0; } private int index(Object key) { //根據(jù)key的hashcode和table長(zhǎng)度取模計(jì)算key在table中的位置 return key.hashCode() % table.length; } public void put(Object key, Object value) { //key為null時(shí)需要特殊處理,為簡(jiǎn)化實(shí)現(xiàn)忽略null值 if (key == null) return; int index = index(key); //遍歷index位置的entry,若找到重復(fù)key則更新對(duì)應(yīng)entry的值,然后返回 HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { entry.setValue(value); return; } entry = entry.getNext(); } //若index位置沒有entry或者未找到重復(fù)的key,則將新key添加到table的index位置 add(index, key, value); } private void add(int index, Object key, Object value) { //將新的entry放到table的index位置第一個(gè),若原來有值則以鏈表形式存放 HashEntry entry = new HashEntry(key, value, table[index]); table[index] = entry; //判斷size是否達(dá)到臨界值,若已達(dá)到則進(jìn)行擴(kuò)容,將table的capacicy翻倍 if (size++ >= threshold) { resize(table.length * 2); } } private void resize(int capacity) { if (capacity <= table.length) return; HashEntry[] newTable = new HashEntry[capacity]; //遍歷原table,將每個(gè)entry都重新計(jì)算hash放入newTable中 for (int i = 0; i < table.length; i++) { HashEntry old = table[i]; while (old != null) { HashEntry next = old.getNext(); int index = index(old.getKey()); old.setNext(newTable[index]); newTable[index] = old; old = next; } } //用newTable替table table = newTable; //修改臨界值 threshold = (int) (table.length * DEFAULT_LOAD_FACTOR); resize++; } public Object get(Object key) { //這里簡(jiǎn)化處理,忽略null值 if (key == null) return null; HashEntry entry = getEntry(key); return entry == null ? null : entry.getValue(); } public HashEntry getEntry(Object key) { HashEntry entry = table[index(key)]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { return entry; } entry = entry.getNext(); } return null; } public void remove(Object key) { if (key == null) return; int index = index(key); HashEntry pre = null; HashEntry entry = table[index]; while (entry != null) { if (entry.getKey().hashCode() == key.hashCode() && (entry.getKey() == key || entry.getKey().equals(key))) { if (pre == null) table[index] = entry.getNext(); else pre.setNext(entry.getNext()); //如果成功找到并刪除,修改size size--; return; } pre = entry; entry = entry.getNext(); } } public boolean containsKey(Object key) { if (key == null) return false; return getEntry(key) != null; } public int size() { return this.size; } public void clear() { for (int i = 0; i < table.length; i++) { table[i] = null; } this.size = 0; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(String.format("size:%s capacity:%s resize:%s\n\n", size, table.length, resize)); for (HashEntry entry : table) { while (entry != null) { sb.append(entry.getKey() + ":" + entry.getValue() + "\n"); entry = entry.getNext(); } } return sb.toString(); } } class HashEntry { private final Object key; private Object value; private HashEntry next; public HashEntry(Object key, Object value, HashEntry next) { this.key = key; this.value = value; this.next = next; } public Object getKey() { return key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public HashEntry getNext() { return next; } public void setNext(HashEntry next) { this.next = next; } }
注:此文章屬懶惰的肥兔原創(chuàng),版權(quán)歸作者和博客園共有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁(yè)面明顯位置給出原文連接
若您覺得這篇文章還不錯(cuò)請(qǐng)點(diǎn)擊下右下角的推薦,有了您的支持才能激發(fā)作者更大的寫作熱情,非常感謝。
如有問題,可以通過lzrabbit@126.com聯(lián)系我。
浙公網(wǎng)安備 33010602011771號(hào)