概述
Java中对于Map数据结构,提供了java.util.Map
接口,该接口下主要有四个常见的实现类,分别是:
HashMap
:根据key.hashCode
计算存储位置,能在\(O(1)\) 完成查询,但是遍历顺序是不确定的,HashMap
最多存储一个键为null,允许多条entry的值为null。HashMap
非线程安全。
HashTable
:线程安全的Map,常用方法全部通过synchronized
保证线程安全,可以使用ConcurrentHashMap
达到目的,此类不建议使用。
LinkedHashMap
:继承自HashMap
,内部通过双向链表将所有entry连接起来,保证了迭代顺序和插入顺序相同。
TreeMap
:实现了SortedMap接口,能够将保存的记录按照键排序。内部通过红黑树进行存储。
HashMap
在JDK 7
中采用了数组+链表的数据结构,在JDK 8
后,底层数据结构转变为:数组+链表+红黑树,也就是当出现Hash冲突时,当链表长度大于阈值(或者红黑树的边界值,默认为8)并且当前数组的长度大于64,链表会转为红黑树存储节点提高搜索效率。
public class HashMap <K,V> extends AbstractMap <K,V> implements Map <K,V>, Cloneable, Serializable
HashMap
继承了 AbstractMap
,该类提供了Map接口的抽象实现,并提供了一些方法的基本实现。实现了
Map
、Cloneable
和
Serializable
接口。
成员变量
loadFactor:该变量控制table数组存放数据的疏密程度,越趋向1时,数组中存放的数据越多越密。链表的长度会增加,因此会导致查找效率变低。该值越小,则数组中存放的数据越少,越稀疏,则会导致空间利用率下降。默认值0.75是较好的默认值,可以最大程度减少rehash的次数,避免过多的性能消耗。
threshold:当前
HashMap
所能容纳键值对数量的最大值,超过这个值,则需扩容。threshold
= capacity * loadFactor
默认容量为16,默认负载因子为0.75,当size达到16 * 0.75 =
12时,需要进行扩容(resize),即默认扩容阈值为12。
扩容倍数为:2倍
DEFAULT_INITIAL_CAPACITY:默认初始容量为16
table:存储Node的数组,链表状态下的节点。
length大小必须为2的n次方,减少hash冲突的现象。
entrySet:存储entry的set集合
size:实际存储的键值对数量
modCount:对map结构操作的次数。
TREEIFY_THRESHOLD:转为红黑树的链表节点阈值(条件之一)。
MIN_TREEIFY_CAPACITY:树化的数组长度阈值(条件之一)。
UNTREEIFY_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 transient Node<K,V>[] table; transient Set<Map.Entry<K,V>> entrySet; transient int size; transient int modCount; int threshold; final float loadFactor;static final int DEFAULT_INITIAL_CAPACITY = 1 << 4 ; static final int MAXIMUM_CAPACITY = 1 << 30 ; static final float DEFAULT_LOAD_FACTOR = 0.75f ; static final int TREEIFY_THRESHOLD = 8 ; static final int UNTREEIFY_THRESHOLD = 6 ; static final int MIN_TREEIFY_CAPACITY = 64 ;
数据结构
链表状态下的节点,继承自Map.Entry<K,V>
。
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 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; } public final K getKey () { return key; } public final V getValue () { return value; } public final String toString () { return key + "=" + value; } public final int hashCode () { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue (V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals (Object o) { if (o == this ) return true ; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true ; } return false ; } }static final int hash (Object key) { int h; return (key == null ) ? 0 : (h = key.hashCode()) ^ (h >>> 16 ); }static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) { Class<?> c; Type[] ts, as; Type t; ParameterizedType p; if ((c = x.getClass()) == String.class) 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) return c; } } } return null ; }
红黑树状态下的节点,继承自LinkedHashMap.Entry<K,V>
,而该类继承自HashMap.Node<K,V>
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 static final class TreeNode <K,V> extends LinkedHashMap .Entry<K,V> { TreeNode<K,V> parent; TreeNode<K,V> left; TreeNode<K,V> right; TreeNode<K,V> prev; boolean red; TreeNode(int hash, K key, V val, Node<K,V> next) { super (hash, key, val, next); }
构造方法
核心的构造方法是第一个,通过调用tableSizeFor
为threshold
(扩容临界值)赋值。
Returns a power of two size for the given target capacity.
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 public HashMap (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); } public HashMap (int initialCapacity) { this (initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap () { this .loadFactor = DEFAULT_LOAD_FACTOR; } public HashMap (Map<? extends K, ? extends V> m) { this .loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false ); }
API
tableSizeFor
该方法在初始化时,对threshold
赋值,通过位运算找到大于或等于cap的最小的2的幂次方。
1 2 3 4 5 6 7 8 9 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 ; }
hash(计算hash值)
该方法在插入时,计算元素的hash值时调用。hash
值为传入key的hashCode
与其右移16位的异或值。这被称为扰动函数 。
1 2 3 4 static final int hash (Object key) { int h; return (key == null ) ? 0 : (h = key.hashCode()) ^ (h >>> 16 ); }
hashCode
方法,是key的类自带的hash方法,返回一个int的Hash值,理论上,这个值应当均匀得分布在int的范围内,但是HashMap
初始化大小为16,如果让hash映射到16个桶中,通过取模实现十分简单。但是直接取模会造成较多的哈希碰撞。扰动函数的作用是:增加了随机性,减少了hash碰撞的几率。
那么如何通过hash值,获取对应的数组下标呢?在putVal
中,获取下标的方法如下:(n - 1) & hash
,n是数组大小,上文中threshold
为2n ,那么(n - 1)
2
=
00....111111,那么通过&
运算,会保留下hash的低位。为何用&
替代取模运算,主要是位运算的效率高于取模运算。这也证明了为何threshold
必须要是2的幂次方,通过控制该值,从而达到提高hash映射效率的目的。
1 if ((p = tab[i = (n - 1 ) & hash]) == null )
get
主要逻辑:
根据hash找到指定位置的节点
判断第一个节点的key是否符合要求,符合要求直接返回第一个节点,否则继续查找。
如果是红黑树结构,通过调用getTreeNode(hash, key)
查找红黑树节点并返回。
如果是链表结构,遍历节点查询并返回
如果没有找到,返回null
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 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 ) { 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 ; }
put
主要逻辑:
若桶数组table为空或length==0,则通过resize()
进行扩容。
根据key的hash得到数组索引,查找要插入的键值对是否已经存在,存在的话,用新值替换旧值。
如果不存在,将键值对插入链表或者红黑树中,并根据长度判断是否将链表转换成红黑树。
判断键值对数量是否大于阈值,大于的话进行扩容操作。
需要注意的是,treeifyBin
方法在进行树化前,进行了检查。如果小于MIN_TREEIFY_CAPACITY
,则进行扩容,不进行树化。
1 if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
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 public V put (K key, V value) { return putVal(hash(key), key, value, false , true ); }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 ; }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); } }
remove
主要逻辑:
判断第一个节点是否是需删除节点,如果是,将节点存储下来。
如果节点是红黑树节点,通过调用getTreeNode
找到需删除节点,存储下来。
如果是链表,遍历获取到需删除节点。
删除节点,并进行修复工作
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 public V remove (Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null , false , true )) == null ? null : e.value; }final Node<K,V> removeNode (int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1 ) & hash]) != null ) { Node<K,V> node = null , e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) node = p; else if ((e = p.next) != null ) { if (p instanceof TreeNode) node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break ; } p = e; } while ((e = e.next) != null ); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this , tab, movable); else if (node == p) tab[index] = node.next; else p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null ; }
resize
HashMap
的table数组长度为2的幂,阈值大小 =
capacity * load factor
(默认阈值为12),Node
数量超过阈值,进行扩容,扩容倍数为2倍。
主要逻辑:
计算新的桶数组容量newCap
和新阈值newThr
。newCap
为原来的两倍,newThr
为原来的两倍。
根据newCap
创建新的桶数组,初始化新的桶数组。
将键值对节点重新映射到新的桶数组中,如果是红黑树节点,则需要拆分红黑树,如果是普通节点,则节点按照顺序进行分组。
需要注意的是:resize
十分消耗性能,日常开发需要尽量避免。方法中变量含义如下:
oldTab:引用扩容前的哈希表
oldCap:表示扩容前的table数组的长度
newCap:扩容之后table数组大小
newThr:扩容之后下次触发扩容的阈值
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 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; @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 { 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; }
红黑树退化
在TreeNode.split
方法和中,有一段代码对是否需要进行退化进行了判断。如果树节点个数小于6
,则会退化为链表,至于该阈值与树化阈值(UNTREEIFY_THRESHOLD 与 TREEIFY_THRESHOLD)
不等的原因,主要为了避免桶数组中的某个节点在该值附近震荡,从而导致频繁的树化和链表化。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 if (loHead != null ) { if (lc <= UNTREEIFY_THRESHOLD) tab[index] = loHead.untreeify(map); else { tab[index] = loHead; if (hiHead != null ) loHead.treeify(tab); } } if (hiHead != null ) { if (hc <= UNTREEIFY_THRESHOLD) tab[index + bit] = hiHead.untreeify(map); else { tab[index + bit] = hiHead; if (loHead != null ) hiHead.treeify(tab); } }
此外,在TreeNode.removeTreeNode
中,删除红黑树节点之前,如果满足以下条件,也会进行链表化再进行删除:
树的左子树为空
树的右子树为空
树的左孙子节点为空
1 2 3 4 5 if (root == null || root.right == null || (rl = root.left) == null || rl.left == null ) { tab[index] = first.untreeify(map); return ; }
线程安全性
HashMap多线程操作存在以下问题:
多线程下扩容形成死循环:JDK1.7中使用头插法插入元素,扩容时可能导致形成环形链表,JDK1.8采用尾插法,不会出现此问题。
多线程put操作导致元素的丢失:多线程put时,发生hash碰撞,会导致key被覆盖,从而导致元素丢失。
put和get并发,导致get为null:线程1执行put,因元素个数超出扩容阈值而导致resize,线程2执行get时,会得到null。
小结
本文对 JDK 8 中的 HashMap
的源代码进行了简要分析,主要为增删改查接口的内部实现机制以及扩容原理。
HashMap内部基于数组实现的,数组每个元素称为一个桶(bucket),当存储的键值对数量超过阈值时,还会进行扩容操作,HashMap中的键值对会重新Hash到新位置。当桶中节点数超过阈值,则会进行树化,如果删除导致低于阈值,则会进行链表化。