Java HashSet(散列集),HashMap(散列映射)的簡單介紹
本篇將簡單講解Java集合框架中的HashSet與HashMap。
散列集(HashSet)快速入門 底層原理:動態(tài)數(shù)組加單向鏈表或紅黑樹。JDK 1.8之后,當(dāng)鏈表長度超過閾值8時,鏈表將轉(zhuǎn)換為紅黑樹。 查閱HashSet的源碼,可以看到HashSet的底層是HashMap,HashSet相當(dāng)于只用了HashMap鍵Key的部分,當(dāng)需要進(jìn)行添加元素操作時,其值Value始終為常量PRESENT = new Object()。以下為HashSet的代碼片段:private transient HashMap<E,Object> map;public HashSet() { map = new HashMap<>();}public boolean add(E e) { return map.put(e, PRESENT)==null;}public Iterator<E> iterator() { return map.keySet().iterator();} 上面說到,在JDK 1.8之后,當(dāng)鏈表長度超過閾值8時,鏈表將轉(zhuǎn)為紅黑樹;當(dāng)鏈表長度小于6時,紅黑樹重新轉(zhuǎn)為鏈表。那么為什么閾值是8呢? 閾值定義為8,符合數(shù)學(xué)概率論上的泊松分布Poisson。根據(jù)泊松分布,一個桶bucket是很難被填滿達(dá)到長度8的。 一旦用于存儲數(shù)據(jù)的鏈表長度達(dá)到閾值8,則很大的可能是該HashSet所使用的散列函數(shù)性能不佳、或存在惡意代碼向集中添加了很多具有相同散列碼的值,此時轉(zhuǎn)為平衡二叉樹可以提高性能。 散列表 鏈表LinkedList、數(shù)組Array或數(shù)組列表ArrayList都有一個共同的缺點:根據(jù)值查找元素速度慢。一旦存放的數(shù)據(jù)較多,查找速度將十分緩慢。 如果應(yīng)用中開發(fā)者不在意元素的排列順序,此時推薦使用的數(shù)據(jù)結(jié)構(gòu)為散列表。散列表用于快速查找對象。 使用散列表的關(guān)鍵是對象必須具備一個散列碼,通過對象內(nèi)HashCode()方法即可計算得到對象的散列碼。一般情況下,不同數(shù)據(jù)的對象將產(chǎn)生不同的散列碼。 下表顯示了使用String類中hashCode()方法成的散列碼: 字符串 散列碼 'Lee' 76268 'lee' 107020 'eel' 100300在Java中,散列表HashTable使用動態(tài)數(shù)組加鏈表或紅黑樹的形式實現(xiàn)。 動態(tài)數(shù)組中的每個位置被稱為桶bucket。要想查找元素位于散列表中的位置,需要首先計算元素的散列碼,然后與桶的總數(shù)取余,所得到的結(jié)果就是保存這個元素的桶的索引。 假設(shè)動態(tài)數(shù)組為table,對象a的散列碼為hashCode,則元素將存放在table的索引為hashCode % table.size(),通常將該索引值成為散列值,它與散列碼是不一樣的。
// HashMap.java源碼// 基于單向鏈表的用于存儲數(shù)據(jù)的對象static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } ...}// 基于紅黑樹的用于存儲數(shù)據(jù)的對象static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> { TreeNode<K,V> parent; // red-black tree links TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; // needed to unlink next upon deletion boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super(hash, key, val, next); } ...}二次散列
散列映射HashMap只對鍵進(jìn)行散列,與鍵關(guān)聯(lián)的值不進(jìn)行散列。以下為HashMap中的部分源碼:
public V put(K key, V value) { return putVal(hash(key), key, value, false, true);}static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);} 所有使用put()方法存入HashMap中的鍵值對,都會在內(nèi)部調(diào)用putVal()進(jìn)行添加元素操作。putVal()方法的第一個參數(shù)則需要提供key的散列碼。 此處并沒有直接使用key.hashCode(),而是使用了HashMap中的hash()方法對key進(jìn)行二次散列。二次散列可以理解為在對象調(diào)用它的散列函數(shù)之后,再進(jìn)行一次額外的計算。二次散列有助于獲得更好的散列碼。 擴(kuò)容機(jī)制 HashMap中的動態(tài)數(shù)組初始容量為16,默認(rèn)的散列因子為0.75,即在容量到達(dá)16 * 0.75 = 12時,會對動態(tài)數(shù)組進(jìn)行擴(kuò)容處理,上限容量被稱為threshold。 擴(kuò)容后的HashMap,其動態(tài)數(shù)組容量為原來的2倍,由于散列因子不會改變,因此threshold也為原來的2倍。 以下為HashMap中resize()、putVal()的源碼:
final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({'rawtypes','unchecked'}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null)loHead = e; elseloTail.next = e; loTail = e; } else { if (hiTail == null)hiHead = e; elsehiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab;}final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 第一個resize()是進(jìn)行動態(tài)數(shù)組Node<K, V>[]初始化的操作,不會進(jìn)行擴(kuò)容 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null); if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; // 當(dāng)HashMap中元素數(shù)量大于閾值threshold,則會進(jìn)行擴(kuò)容resize()操作 if (++size > threshold) resize(); afterNodeInsertion(evict); return null;} 通過源碼可以知道,HashMap在初始化的時候并不會立即為動態(tài)數(shù)組分配內(nèi)存,直到調(diào)用putVal()為止,才會在putVal()中調(diào)用resize()方法初始化動態(tài)數(shù)組。 動態(tài)數(shù)組Node<K, V>[]將在resize()中完成初始化或擴(kuò)容的操作。 其中有關(guān)初始化的關(guān)鍵代碼為:
newCap = DEFAULT_INITIAL_CAPACITY; // DEFAULT_INITIAL_CAPACITY = 1 << 4,即默認(rèn)大小為16。newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // threshold = newCap * 0.75,即默認(rèn)為12。 有關(guān)于擴(kuò)容的關(guān)鍵代碼為:
if (oldCap > 0) { // 當(dāng)動態(tài)數(shù)組擁有默認(rèn)容量時,如果再次調(diào)用resize(),則一定會進(jìn)行擴(kuò)容操作 if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) { // 容量為原來的2倍 newThr = oldThr << 1; // 閾值為原來的2倍 }}總結(jié)
以上為所有關(guān)于HashSet、HashMap的粗略介紹。如果希望了解更多的內(nèi)容,可以前往JDK閱讀源碼。
以上就是Java HashSet(散列集),HashMap(散列映射)的簡單介紹的詳細(xì)內(nèi)容,更多關(guān)于Java HashSet和HashMap的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
