前言
回想之前几次的面试,没有一次不问到 hashmap 的,这也体现了 hashmap 的重要性了。记得当时的回答是底层是数组加链表的方式实现的,然后就是什么 get 时候怎么查找的。现在想想这些小白都知道的东西说出来也加不了分啊。现在挤点时间出来看看源码吧。
底层实现简介
数组加链表这个没什么好说的,看下面这个图就能明白了(java8当中当链表达到一定长度就会转换成红黑树,这个之后再说)。还是从源码来看吧,这里时间问题不可能每个方法都拿出来讲了,挑几个重要的方法来说。

HashMap(int, float)
第一个参数是容量默认为16,第二个参数是负载因子默认是0.75。源码如下:
123456789101112 | public (int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > 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) 这个方法,由于 hashmap 的容量总是2的幂,所以这个方法就是找到大于等于 initialCapacity 的最小的2的幂
123456789101112 | /** * Returns a power of two size for the given target capacity. */static final int tableSizeFor(int cap) { //例如cap = 10 int n = cap - 1; n |= n >>> 1; //n = n|n无符号右移1位 1001|0100 = 1101 n |= n >>> 2; //n = n|n无符号右移2位 1101|0011 = 1111 n |= n >>> 4; //n = n|n无符号右移4位 1111|0000 = 1111 n |= n >>> 8; //n = n|n无符号右移8位 1111|0000 = 1111 n |= n >>> 16; //n = n|n无符号右移16位 1111|0000 = 1111 return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; //返回16} |
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)
123 | public V put(K key, V value) { return putVal(hash(key), key, value, false, true);} |
1234 | static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); //为了hash碰撞的概率} |
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 | /** * 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 */ 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) //第一次put操作的时候会resize,稍后再看 n = (tab = resize()).length; //当前index在数组中的位置的链表头节点空的话则直接创建一个新节点 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { Node<K,V> e; K k; //key相等且hash也相等,则是覆盖value操作 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); //如果追加节点后,链表长度>=8,则转化为红黑树 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } //遍历链表的过程中也可能存在hash和key都相等的情况 if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) break; //把e赋给p就是让链表一步一步往下走 p = e; } } //e不为null则代表将要被覆盖value的那个节点 if (e != null) { // existing mapping for key V oldValue = e.value; // onlyIfAbsent为true的话则不改变已经存在的value(不包括null噢) if (!onlyIfAbsent || oldValue == null) e.value = value; //这个在linkedhashmap中实现 afterNodeAccess(e); return oldValue; } } //这里代表插入了一个新的链表节点,修改modCount,返回null ++modCount; //更新hashmap的size,并判断是否需要resize if (++size > threshold) resize(); afterNodeInsertion(evict); return null;} |
resize( )
这个方法会在初始化和 size 超过 threshold 的时候执行。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 | /** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; //在hashmap(int, float)构造方法中已经将 tableSizeFor 的返回值赋值给了 threshold int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { //容量已达上限,则设置阈值是2的31次方-1,同时不再扩容 threshold = Integer.MAX_VALUE; return oldTab; } //未达上限则扩容一倍 else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } //用上面的 tableSizeFor 返回值作为初始容量 else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; //代表是没有容量/阈值参数的情况 else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; //16 newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); //0.75*16 } //对应的是上面几行那个else if(oldThr > 0)的情况 if (newThr == 0) { float ft = (float)newCap * loadFactor; //对阀值越界情况修复为 Integer.MAX_VALUE newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; ({"rawtypes","unchecked"}) //构造新的table数组 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) { //不能有了老婆忘了娘吧,这里给原来的置为null oldTab[j] = null; if (e.next == null) //要时刻记得index = hash & (table.length-1) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); //当前链表上不止一个节点 else { // preserve order //因为扩容是翻倍的,所以原链表上的每个节点,在扩容后的哈希桶中,要么还在原来下标位(low位),要么在旧下标+旧容量(high位) //low位头节点、尾节点 Node<K,V> loHead = null, loTail = null; //high位头节点、尾节点 Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; //这里就很关键了,靠 e.hash & oldCap 来区分low位还是high位,稍后详细说下 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; } //可以看出low位和high位差一个旧容量 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)
1234 | public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value;} |
123456789101112131415161718192021 | 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 && // 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); } } return null;} |
红黑树相关方法
红黑树相关知识网上有很多不错的讲解,推荐一个github地址,感兴趣可以去看一下,教你透彻了解红黑树
先来 TreeNode 有什么属性吧
12345 | TreeNode<K,V> parent; // red-black tree linksTreeNode<K,V> left;TreeNode<K,V> right;TreeNode<K,V> prev; // needed to unlink next upon deletionboolean red; |
记得之前在 putVal( ) 方法中,如果追加节点后链表长度>=8就会转换为树。其中 treeifyBin(tab, hash) 方法如下
123456789101112131415161718192021 | 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 { //根据e节点构建一个新的treeNode 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)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 | 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; //此处执行,就是把hd作为根节点,设置red为false 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; //根据当前节点的hash与root的hash大小区别开 if ((ph = p.hash) > h) dir = -1; else if (ph < h) dir = 1; else if ((kc == null && //hash相同则判断key是否实现了Comparable接口 (kc = comparableClassFor(k)) == null) || //实现了Comparable接口则直接比较 (dir = compareComparables(kc, k, pk)) == 0) //否则调用System.identityHashCode比较,这里就不研究了 dir = tieBreakOrder(k, pk); TreeNode<K,V> xp = p; if ((p = (dir <= 0) ? p.left : p.right) == null) { //把当前节点parent指向root x.parent = xp; //如果dir<=0,也就是当前节点的hash<=root的hash,把root的left指向当前节点 if (dir <= 0) xp.left = x; //如果dir>0,也就是当前节点的hash>root的hash,把root的right指向当前节点 else xp.right = x; //此处进行插入平衡操作,重新指定root,稍后再说 root = balanceInsertion(root, x); break; } } } } //恢复root的位置,即起点作为根节点 moveRootToFront(tab, root);} |
接着看下 balanceInsertion(root, x)怎么重新指定root的
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 | 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;;) { //如果当前节点父节点为null,则令其为黑色,直接返回当前节点 if ((xp = x.parent) == null) { x.red = false; return x; } //如果当前节点父节点为黑色,或者祖父节点为null,直接返回root else if (!xp.red || (xpp = xp.parent) == null) return root; //如果当前节点的父节点是祖父节点的左孩子 if (xp == (xppl = xpp.left)) { //如果当前节点的祖父节点的右孩子不为null并且为红色,则令其为黑色 //并且令父节点为黑色,令祖父节点为红色,把祖父节点设置为当前节点 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 { //祖父节点左孩子不为null且为红色 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
12345
@Overridepublic V getOrDefault(Object key, V defaultValue) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;}
存在则不覆盖的put,调用putVal( )
1234
@Overridepublic V putIfAbsent(K key, V value) { return putVal(hash(key), key, value, true, true);}
根据key和value移除
1234
@Overridepublic boolean remove(Object key, Object value) { return removeNode(hash(key), key, value, true, true) != null;}
还有一些其它的方法没有说到,感兴趣的可以去看下源码。
LinkedHashMap
顺便简单说下 LinkedHashMap 吧,与 HashMap 最主要的区别是,其内部维护的双向链表,可以按照插入顺序或者最近访问顺序遍历取值。
12345 | public LinkedHashMap() { super(); //false则按插入顺序,true则按最近访问顺序 accessOrder = false;} |
123456 | public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder;} |
其中用 Entry<K, V> 继承了 HashMap.Node<K, V>,通过 before 和 after 实现了双向链表
123456 | 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)
12345678 | 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;} |
12345678910111213141516171819202122232425262728293031323334 | void afterNodeAccess(Node<K,V> e) { // move node to last LinkedHashMap.Entry<K,V> last; //如果accessOrder为true且e不是tail if (accessOrder && (last = tail) != e) { //让p指向当前e节点,且让b指向前节点,a指向后节点 LinkedHashMap.Entry<K,V> p = (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after; //让p(指向e)的after为null,后面会让tail指向它 p.after = null; //如果前节点b为null,则让head指向后节点a if (b == null) head = a; //否则前节点b的after指向后节点a else b.after = a; //如果后节点a不为null,则让a的before指向前节点b if (a != null) a.before = b; //否则,让last指向b else last = b; //如果last为null,则让head指向p if (last == null) head = p; //否则,让p的before指向last,last的after指向p else { p.before = last; last.after = p; } //让tail指向p tail = p; ++modCount; }} |
如果 accessOrder 为 true,上面的操作就是调整 get 的那个节点e至尾部,且修复之前e节点的前节点的 after 指针,后节点的 before 指针的指向。
至于 HashMap 预留给 LinkedHashMap 的 afterNodeAccess()、afterNodeInsertion() 、afterNodeRemoval() 方法 平时不怎么用到,这里不做介绍了。