我對紅黑樹不是很瞭解,因此解說不是很好。還有remove等方法沒寫,之後再說。linkedHashMap,treeMap,也在說java
hashMap由數組、鏈表、紅黑樹組成。node
why?bootstrap
數組,查找快!只要知道下標,Array[index]就查到了,可是向指定下標插入一個值,當該位置有值(我稱之爲原值)時,則要考慮原值的去留問題!數組
鏈表,插入、刪除快!只要更改prev、next的指向便可,可是,查找慢,得一個個遍歷!數據結構
紅黑樹,插入、查找、刪除都快!可是比較複雜。後面有時間,我會慢慢搞透他!app
以下圖所示:less
圖一 hashMap基礎數據結構函數
hashMap由 transient Node<K,V>[] table (這就是數組) 組成。Node包含鍵值等屬性post
/** * 基本的桶節點,大多數實體都會用到:存儲的<key,value>對應Node的key,value * Basic hash bin node, used for most entries. (See below for * TreeNode subclass, and in LinkedHashMap for its Entry subclass.) */ 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; } ... }
treeNode是紅黑樹的結點,是Node的子類this
/** * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn * extends Node) so can be used as extension of either regular or * linked node. */ 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; ... }
/** * The table, initialized on first use, and resized as * necessary. When allocated, length is always a power of two. * (We also tolerate length zero in some operations to allow * bootstrapping mechanics that are currently not needed.) */ transient Node<K,V>[] table; /** * Holds cached entrySet(). Note that AbstractMap fields are used * for keySet() and values(). */ transient Set<Map.Entry<K,V>> entrySet; /** * The number of key-value mappings contained in this map. */ transient int size; /** * The number of times this HashMap has been structurally modified * Structural modifications are those that change the number of mappings in * the HashMap or otherwise modify its internal structure (e.g., * rehash). This field is used to make iterators on Collection-views of * the HashMap fail-fast. (See ConcurrentModificationException). */ transient int modCount; /** * The next size value at which to resize (capacity * load factor). * * @serial */ // (The javadoc description is true upon serialization. // Additionally, if the table array has not been allocated, this // field holds the initial array capacity, or zero signifying // DEFAULT_INITIAL_CAPACITY.) int threshold; /** * The load factor for the hash table. * * @serial */ final float loadFactor;
一共有4種構造方法,DEFAULT_LOAD_FACTOR = 0.75f
public HashMap(int initialCapacity, float loadFactor) //指定table[]初始大小和負載因子 public HashMap(int initialCapacity) { //指定table[]初始大小 this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap() { //無參構造函數 this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } public HashMap(Map<? extends K, ? extends V> m) { //根據舊map,生成新map this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); }
重點看第一種
public HashMap(int initialCapacity, float loadFactor) { //初始化大小 和 負載因子 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) //MAXIMUM_CAPACITY = 1 << 30 initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); }
調用了tableSizeFor(initialCapacity),做用是返回>=初始化大小的 最小的 2的n次方。如1->2,15->16,32->32...上圖中將tableSize賦給threshold,在後期會付給table數組的初始化大小——table[]的size始終是2的n次方!這便於快速定位數組的下標( key.hashCode&(table.size-1) )
/** * Returns a power of two size for the given target capacity. */ static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1;//無符號右移1位(2進制) n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
4種構造方法,有三種未初始化table數組,這是一種懶加載機制——(並不須要一開始就建立數組,而是須要用到他的時候建立,好比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) { 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);//哈希值與他的無符號高16位 亦或 }
/** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none(若是該key存在對應的value,則修改,並返回舊值。若是不存在,插入,並返回null) */ 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)//用本地變量tab指向全局table[], n = (tab = resize()).length; //若是table[]沒有初始化,調用resize初始化,n爲table的長度 if ((p = tab[i = (n - 1) & hash]) == null) //(n - 1) & hash,表明該key在table中的下標,記爲 位置A,p指向位置A的,惟一的Node,或鏈表、紅黑樹的頭結點 tab[i] = newNode(hash, key, value, null); //若是位置A沒有值,則新建一個Node,next=null else { //若是位置A有值,則根據實際狀況:1.修改 2.插入鏈表 3.插入紅黑樹 Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; //key與p.key相同,作修改操做(此時,p多是單節點,或鏈表、樹的頭,可是不重要,由判斷條件知道,K要重寫equals和hashCode方法) else if (p instanceof TreeNode) //key與p.key不相同,且p是紅黑樹的節點(頭結點) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);//修改或插入紅黑樹 else { //p是鏈表的(頭)結點 for (int binCount = 0; ; ++binCount) { //遍歷鏈表 if ((e = p.next) == null) { //到了鏈表的尾部-tail p.next = newNode(hash, key, value, null);//建立一個新節點到尾部 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st(鏈表長度大於等於8時,將鏈表轉成紅黑樹) treeifyBin(tab, hash); //轉成紅黑樹,或擴容 break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))//key徹底相同,則替換值 break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); // Callbacks to allow LinkedHashMap post-actions return oldValue; } } ++modCount; //走到這一步、說明有新節點加入。modCount,本map的修改次數,便利時用到,防止concurrentModifition if (++size > threshold) //若是map的大小超過閥值,擴容(1.7版 會rehash) resize(); afterNodeInsertion(evict); // Callbacks to allow LinkedHashMap post-actions return null; }
/** * Tree version of putVal. */ final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab, int h, K k, V v) { Class<?> kc = null; boolean searched = false; TreeNode<K,V> root = (parent != null) ? root() : this; for (TreeNode<K,V> p = root;;) { int dir, ph; K pk; if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((pk = p.key) == k || (k != null && k.equals(pk))) return p; else if ((kc == null && (kc = comparableClassFor(k)) == null) || (dir = compareComparables(kc, k, pk)) == 0) { if (!searched) { TreeNode<K,V> q, ch; searched = true; if (((ch = p.left) != null && (q = ch.find(h, k, kc)) != null) || ((ch = p.right) != null && (q = ch.find(h, k, kc)) != null)) return q; } dir = tieBreakOrder(k, pk); } TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { Node<K,V> xpn = xp.next; TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn); if (dir <= 0) xp.left = x; else xp.right = x; xp.next = x; x.parent = x.prev = xp; if (xpn != null) ((TreeNode<K,V>)xpn).prev = x; moveRootToFront(tab, balanceInsertion(root, x)); return null; } } }
不太懂
/** * Replaces all linked nodes in bin at index for given hash unless * table is too small, in which case resizes instead. */ final void treeifyBin(Node<K,V>[] tab, int hash) { int n, index; Node<K,V> e; if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY) resize(); else if ((e = tab[index = (n - 1) & hash]) != null) { TreeNode<K,V> hd = null, tl = null; do { TreeNode<K,V> p = replacementTreeNode(e, null); if (tl == null) hd = p; else { p.prev = tl; tl.next = p; } tl = p; } while ((e = e.next) != null); if ((tab[index] = hd) != null) hd.treeify(tab); } }
小總結:put<key, value>操做,包含着插入、修改兩重語義。當map中存在該key時,執行修改操做,比較簡單。當map中不存在該key,執行插入操做,該操做會致使插入鏈表 || map擴容 || 鏈表轉紅黑樹 || 插入紅黑樹,並修改全局變量modCount,若是遍歷(for循環)map時執行put操做,可能會致使concurrentModifitionException,可使用concurrentHashMap代替,後期會講它
public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } final Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //hashMap經過(length - 1) & hash快速定位,這是數組的優勢 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k))))//若是是鏈表的頭結點/樹的根節點,直接返回 return first; if ((e = first.next) != null) { if (first instanceof TreeNode) //是樹節點,則經過樹的方式(左子節點-右子節點-左...)返回, return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); //是鏈表,則遍歷(鏈表最大長度爲8) } } return null; } /** * Calls find for root node. */ final TreeNode<K,V> getTreeNode(int h, Object k) { return ((parent != null) ? root() : this).find(h, k, null); //先獲取樹的root結點,而後調用find方法 } /** * Returns root of tree containing this node. */ final TreeNode<K,V> root() { for (TreeNode<K,V> r = this, p;;) { if ((p = r.parent) == null) return r; r = p; } } /** * Finds the node starting at root p with the given hash and key. * The kc argument caches comparableClassFor(key) upon first use * comparing keys. */ final TreeNode<K,V> find(int h, Object k, Class<?> kc) { TreeNode<K,V> p = this; do { int ph, dir; K pk; //ph-當前結點的hash TreeNode<K,V> pl = p.left, pr = p.right, q; //hash = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16) if ((ph = p.hash) > h) //若是h<當前結點的hash,p = p的左子節點 p = pl; else if (ph < h) //若是h>當前結點的hash,p = p的右子節點 p = pr; else if ((pk = p.key) == k || (k != null && k.equals(pk)))//key相同,直接返回 return p; else if (pl == null) p = pr; else if (pr == null) p = pl; else if ((kc != null || (kc = comparableClassFor(k)) != null) && (dir = compareComparables(kc, k, pk)) != 0) p = (dir < 0) ? pl : pr; else if ((q = pr.find(h, k, kc)) != null) return q; else p = pl; } while (p != null); return null; }
上面用到兩個方法,頗有意思,能夠本身意會
/** * Returns x's Class if it is of the form "class C implements * Comparable<C>", else null. */ static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) { Class<?> c; Type[] ts, as; Type t; ParameterizedType p; if ((c = x.getClass()) == String.class) // bypass checks return c; if ((ts = c.getGenericInterfaces()) != null) { for (int i = 0; i < ts.length; ++i) { if (((t = ts[i]) instanceof ParameterizedType) && ((p = (ParameterizedType)t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) // type arg is c return c; } } } return null; }
/** * Returns k.compareTo(x) if x matches kc (k's screened comparable * class), else 0. */ @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); }