标签:let 不能 赋值 oat either otherwise jpg extend size
前言 回想之前几次的面试,没有一次不问到 hashmap 的,这也体现了 hashmap 的重要性了。记得当时的回答是底层是数组加链表的方式实现的,然后就是什么 get 时候怎么查找的。现在想想这些小白都知道的东西说出来也加不了分啊。现在挤点时间出来看看源码吧。
底层实现简介 数组加链表这个没什么好说的,看下面这个图就能明白了(java8当中当链表达到一定长度就会转换成红黑树,这个之后再说)。还是从源码来看吧,这里时间问题不可能每个方法都拿出来讲了,挑几个重要的方法来说。
HashMap(int, float) 第一个参数是容量默认为16,第二个参数是负载因子默认是0.75。源码如下:
1 2 3 4 5 6 7 8 9 10 11 12 public (int initialCapacity, float loadFactor) { if (initialCapacity < 0 ) throw new IllegalArgumentException("Illegal initial capacity: " initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) 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) 这个方法,由于 hashmap 的容量总是2的幂,所以这个方法就是找到大于等于 initialCapacity 的最小的2的幂
1 2 3 4 5 6 7 8 9 10 11 12 static final int tableSizeFor (int cap) { int n = cap - 1 ; n |= n >>> 1 ; n |= n >>> 2 ; n |= n >>> 4 ; n |= n >>> 8 ; n |= n >>> 16 ; return (n < 0 ) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n 1 ; }
tableSizeFor 方法为什么这么设计呢, 我们假设假设n只有最高位是1后面低位全是0,和无符号右移1位相或,得到最高位、次高位是1,后面低位均是0。再与无符号右移2位相或,得到高四位是1后面均是0。下面同理,或上无符号右移4位,得到高8位是1。或上无符号右移8位,得到高16位为1。或上无符号右移16位,得到32位全是1。此时已经大于 MAXIMUM_CAPACITY 了,没必要继续了。返回 MAXIMUM_CAPACITY 即可。这是在cap <= MAXIMUM_CAPACITY 最极致的情况了。
tableSizeFor 方法返回值赋值给了 threshold ?为什么不是下面这样了
1 this .threshold = tableSizeFor(initialCapacity) * this .loadFactor;
在这个构造方法中并没有对 table 数组初始化,初始化是第一次 put 操作的时候进行的,到时候会对 threshold 重新进行计算,这个不用我们担心??。
put(K, V) 1 2 3 public V put (K key, V value) { return putVal(hash(key), key, value, false , true ); }
1 2 3 4 static final int hash (Object key) { int h; return (key == null ) ? 0 : (h = key.hashCode()) ^ (h >>> 16 ); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 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; 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 ) treeifyBin(tab, hash); break ; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break ; p = e; } } if (e != null ) { V oldValue = e.value; if (!onlyIfAbsent || oldValue == null ) e.value = value; afterNodeAccess(e); return oldValue; } } modCount; if ( size > threshold) resize(); afterNodeInsertion(evict); return null ; }
resize( ) 这个方法会在初始化和 size 超过 threshold 的时候执行。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 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 ; } else if (oldThr > 0 ) newCap = oldThr; else { 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; ({"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 { 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; else loTail.next = e; loTail = e; } else { if (hiTail == null ) hiHead = e; else hiTail.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; }
简单说下上面怎么区分原来链表的节点是应该放在 low 位还是 high 位的,假设一个 key 的 hash 为 00001100,哈希桶的容量是16,也就是 00010000。那么 00001100 & 00001111 = 00001100,也就是角标为12的桶中,而另一个 key 的 hash 为00011100,00011100 & 00001111 = 00001100,那么它也在角标为12的桶中。但是这两个 key 的 hash 分别和 00010000 相与,结果刚好差了一个旧容量的大小。也就是根据 key 的 hash 和旧容量为1的那位对应的是0还是1,是0的话就放在 low 位,是1就放在 high 位。
get(Object) 1 2 3 4 public V get (Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 final Node<K,V> getNode (int hash, Object key) { Node<K,V>[] tab; Node<K,V> 大专栏 JAVA8的HashMap; first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1 ) & hash]) != null ) { if (first.hash == hash && ((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 ); } } return null ; }
红黑树相关方法 红黑树相关知识网上有很多不错的讲解,推荐一个github地址,感兴趣可以去看一下,教你透彻了解红黑树
先来 TreeNode 有什么属性吧
1 2 3 4 5 TreeNode<K,V> parent; TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; boolean red;
记得之前在 putVal( ) 方法中,如果追加节点后链表长度>=8就会转换为树。其中 treeifyBin(tab, hash) 方法如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 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); } }
现在 hd 就是之前链表头节点转换成的 treeNode,它的 next 指向下一个 treeNode,并且这个 treeNode 的 prev 指向 hd,后面同理。然后来看下 hd.treeify(tab)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 final void treeify (Node<K,V>[] tab) { TreeNode<K,V> root = null ; for (TreeNode<K,V> x = this , next; x != null ; x = next) { next = (TreeNode<K,V>)x.next; x.left = x.right = null ; if (root == null ) { x.parent = null ; x.red = false ; root = x; } else { K k = x.key; int h = x.hash; Class<?> kc = null ; for (TreeNode<K,V> p = root;;) { int dir, ph; K pk = p.key; if ((ph = p.hash) > h) dir = -1 ; else if (ph < h) dir = 1 ; else if ((kc == null && (kc = comparableClassFor(k)) == null ) || (dir = compareComparables(kc, k, pk)) == 0 ) dir = tieBreakOrder(k, pk); TreeNode<K,V> xp = p; if ((p = (dir <= 0 ) ? p.left : p.right) == null ) { x.parent = xp; if (dir <= 0 ) xp.left = x; else xp.right = x; root = balanceInsertion(root, x); break ; } } } } moveRootToFront(tab, root); }
接着看下 balanceInsertion(root, x)怎么重新指定root的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 static <K,V> TreeNode<K,V> balanceInsertion (TreeNode<K,V> root, TreeNode<K,V> x) { x.red = true ; for (TreeNode<K,V> xp, xpp, xppl, xppr;;) { if ((xp = x.parent) == null ) { x.red = false ; return x; } else if (!xp.red || (xpp = xp.parent) == null ) return root; if (xp == (xppl = xpp.left)) { if ((xppr = xpp.right) != null && xppr.red) { xppr.red = false ; xp.red = false ; xpp.red = true ; x = xpp; } else { if (x == xp.right) { root = rotateLeft(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null ) { xp.red = false ; if (xpp != null ) { xpp.red = true ; root = rotateRight(root, xpp); } } } } else { if (xppl != null && xppl.red) { xppl.red = false ; xp.red = false ; xpp.red = true ; x = xpp; } else { if (x == xp.left) { root = rotateRight(root, x = xp); xpp = (xp = x.parent) == null ? null : xp.parent; } if (xp != null ) { xp.red = false ; if (xpp != null ) { xpp.red = true ; root = rotateLeft(root, xpp); } } } } } }
上面这个方法看不懂的话主要还是红黑树没有理解。建议先理解下红黑树。移除修复操作大同小异,这里就不做记录了。
其他新增方法
带有默认值的get
1 2 3 4 5 @Override public V getOrDefault (Object key, V defaultValue) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? defaultValue : e.value; }
存在则不覆盖的put,调用putVal( )
1 2 3 4 @Override public V putIfAbsent (K key, V value) { return putVal(hash(key), key, value, true , true ); }
根据key和value移除
1 2 3 4 @Override public boolean remove (Object key, Object value) { return removeNode(hash(key), key, value, true , true ) != null ; }
还有一些其它的方法没有说到,感兴趣的可以去看下源码。
LinkedHashMap 顺便简单说下 LinkedHashMap 吧,与 HashMap 最主要的区别是,其内部维护的双向链表,可以按照插入顺序或者最近访问顺序遍历取值。
1 2 3 4 5 public LinkedHashMap () { super (); accessOrder = false ; }
1 2 3 4 5 6 public LinkedHashMap (int initialCapacity, float loadFactor, boolean accessOrder) { super (initialCapacity, loadFactor); this .accessOrder = accessOrder; }
其中用 Entry<K, V> 继承了 HashMap.Node<K, V>,通过 before 和 after 实现了双向链表
1 2 3 4 5 6 static class Entry <K ,V > extends .Node <K ,V > { Entry<K,V> before, after; Entry(int hash, K key, V value, Node<K,V> next) { super (hash, key, value, next); } }
get(Object) 1 2 3 4 5 6 7 8 public V get (Object key) { Node<K,V> e; if ((e = getNode(hash(key), key)) == null ) return null ; if (accessOrder) afterNodeAccess(e); return e.value; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 void afterNodeAccess (Node<K,V> e) { LinkedHashMap.Entry<K,V> last; if (accessOrder && (last = tail) != e) { LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; p.after = null ; if (b == null ) head = a; else b.after = a; if (a != null ) a.before = b; else last = b; if (last == null ) head = p; else { p.before = last; last.after = p; } tail = p; modCount; } }
如果 accessOrder 为 true,上面的操作就是调整 get 的那个节点e至尾部,且修复之前e节点的前节点的 after 指针,后节点的 before 指针的指向。
至于 HashMap 预留给 LinkedHashMap 的 afterNodeAccess()、afterNodeInsertion() 、afterNodeRemoval() 方法 平时不怎么用到,这里不做介绍了。
JAVA8的HashMap
标签:let 不能 赋值 oat either otherwise jpg extend size