java.util.HashMap
本文目录:
- 一、HashMap 的特点概述和说明
- 二、HashMap 的内部实现:从内部属性和构造函数说起
- 三、HashMap 的 put 操作
- 四、HashMap 的扩容
- 五、HashMap 的 get 操作
- 六、HashMap 的 remove 操作
- 七、参考
一、HashMap的特点概述和说明
关注点 | HashMap的相关结论 |
是否允许空的 key | 是 |
是否允许重复的 key | 否,实际上可能会进行覆盖更新 |
元素有序:读取数据和存放数据的顺序一致 | 否,读取和存放都无序 |
是否线程安全 | 否 |
通过 key 进行随机访问的效率 | 较快 |
添加元素的效率 |
较快 涉及扩容、列表转红黑树、遍历列表时相对慢 |
删除元素的效率 | 较快 |
这里主要提几点:
- Java8 中 HashMap 源码的大方向就是:数组 + 单向链表(数组的元素,Node 实例,包含四个属性:key, value, hash 值和用于单向链表的 next) + 红黑树(链表超过8个元素且总元素个数超过 64 时转换为红黑树),对于hash冲突的元素,使用链表进行存储,每次存储在链表末尾。
- capacity:当前数组容量,默认值是 16,自动扩容,但始终保持 2^n,即扩容后数组大小为当前的 2 倍。
- loadFactor:负载因子,默认为 0.75。
- threshold:扩容的阈值,等于 capacity * loadFactor,当元素实际个数 size 大于等于 threshold 时,进行扩容。
Java8的 HashMap,最大的改变,是使用了数组 + 链表 + 红黑树。当链表中的元素达到了 8 个且总元素个数超过64个时,会将链表转换为红黑树,在这些位置进行查找的时候可以由原来的耗时 O(N),降低到时间复杂度为 O(logN)。另附上简要示意图:
二、HashMap的内部实现:从内部属性和构造函数说起
1、常用的类属性
常用的类属性如下,比如默认容量、负载因子等。
/** * The default initial capacity - MUST be a power of two. * 默认的初始容量 16 = 2 ^ 4 */ static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 /** * The maximum capacity, used if a higher value is implicitly specified * by either of the constructors with arguments. * MUST be a power of two <= 1<<30. * 允许的最大容量 */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The load factor used when none specified in constructor. * 默认的负载因子 */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2 and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. * 达到需要转化为红黑树时的链表容量阈值 */ static final int TREEIFY_THRESHOLD = 8; /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. * 红黑树转回链表的下限阈值 */ static final int UNTREEIFY_THRESHOLD = 6; /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts * between resizing and treeification thresholds. * 达到需要转化为红黑树时的Map总容量最低阈值 */ static final int MIN_TREEIFY_CAPACITY = 64;
2、实例属性
实例属性,包括内部实际存储元素的数组、Map 的实际大小、实际的负载因子、修改次数等
/** * 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. * 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). * 修改次数,用于 fail-fast 机制校验 */ 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;
3、节点内部类
这个是实际的元素存储节点。
/** * 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; ... }
4、构造函数
几个构造函数中最主要的还是要设定初始的负载因子 loadFactor。
/** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and load factor. * 指定 初始容量 和 负载因子 * @param initialCapacity the initial capacity * @param loadFactor the load factor * @throws IllegalArgumentException if the initial capacity is negative * or the load factor is nonpositive */ 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; // 设定阈值为 大于等于指定初始容量且最小 的 2^n this.threshold = tableSizeFor(initialCapacity); } /** * Constructs an empty <tt>HashMap</tt> with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity. * @throws IllegalArgumentException if the initial capacity is negative. */ public HashMap(int initialCapacity) { // 使用默认的负载因子 0.75 this(initialCapacity, DEFAULT_LOAD_FACTOR); } /** * Constructs an empty <tt>HashMap</tt> with the default initial capacity * (16) and the default load factor (0.75). */ public HashMap() { // 使用默认负载因子 0.75,而其他使用默认值,包括 阈值 threshold = 0 this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } /** * Constructs a new <tt>HashMap</tt> with the same mappings as the * specified <tt>Map</tt>. The <tt>HashMap</tt> is created with * default load factor (0.75) and an initial capacity sufficient to * hold the mappings in the specified <tt>Map</tt>. * * @param m the map whose mappings are to be placed in this map * @throws NullPointerException if the specified map is null */ public HashMap(Map<? extends K, ? extends V> m) { // 使用默认的负载因子 0.75 this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false); } /** * Implements Map.putAll and Map constructor * * @param m the map * @param evict false when initially constructing this map, else * true (relayed to method afterNodeInsertion). */ final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) { int s = m.size(); if (s > 0) { if (table == null) { // pre-size,说明还没有初始化,进行阈值的预设定 float ft = ((float)s / loadFactor) + 1.0F; int t = ((ft < (float)MAXIMUM_CAPACITY) ? (int)ft : MAXIMUM_CAPACITY); if (t > threshold) threshold = tableSizeFor(t); // 大于等于指定容量且最小 的 2^n } else if (s > threshold) resize(); // 先进行一次扩容 for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) { K key = e.getKey(); V value = e.getValue(); putVal(hash(key), key, value, false, evict); // 内部还会检查是否需要扩容 } } }
三、HashMap 的 put 操作
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); } /** * 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 * onlyIfAbsent 为 true 时表示不修改已存在的(key 对应的)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; // 因为前面构造器都没有对数组 table 进行初始化,因此第一次进行put操作时需要进行扩容 // 由于 table 本身为 null,最终也只是新建大小为默认容量 16 的数组而已 if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; // 当前 key 对应的具体数组下标,如果对应数组元素为 null,则直接初始化 Node 元素并设置即可 if ((p = tab[i = (n - 1) & hash]) == null) tab[i] = newNode(hash, key, value, null); else { // 说明该下标位置存在相关的元素数据 Node<K,V> e; K k; // 数组对应位置的元素的 key 与 put 操作的 key “相等” if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) e = p; // 否则需要判断是链表还是红黑树来执行 put 操作 // 红黑树节点则按照红黑树的插值方法进行 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); // binCount 为 7 时触发红黑树转化,明显此时0-6已经有节点了, // 再加上原来的 tab[i](相当于 -1),新插入的是链表的第9个位置 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } // put 操作的 key 与链表中的该位置的 key “相等” if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) // 说明在链表中存在并找到了与 key 一致的节点 break; p = e; } } // 存在旧的 key 与要 put 的 key 一致,考虑是否进行值覆盖,然后返回旧值 if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } // 记录修改次数 ++modCount; // 超过阈值,则进行扩容 if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
四、HashMap 的扩容
HashMap扩容的过程也就是内部数组的扩容,源码如下:
/** * 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; 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 阈值扩大一倍 } // 有进行初始化容量的设定时会设置 threshold,此时的第一次 put 操作进入这里 else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults // 没有指定初始容量的 new HashMap(),第一次 put 操作进入这里 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 // 链表情况下的迁移 // 将链表拆成两个链表,放到新的数组中,并且保留原来的先后顺序 // loHead、loTail 对应一条链表,hiHead、hiTail 则对应另一条链表 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; // 第二条链表的新的位置是 j + oldCap,也比较好理解 newTab[j + oldCap] = hiHead; } } } } } return newTab; }
五、HashMap 的 get 操作
get 操作比较直接,流程大致如下:
- 计算 key 的 hash 值,根据 hash 找到对应的数组下标即 (table.length - 1) & hash;
- 判断对应下标处的节点元素是否正好是要寻找,如是即返回;否,继续下一步;
- 如果是红黑树,则用红黑树的方法获取数据;
- 如果是链表,则按照链表的方式寻找相应的节点;
- 找不到的,返回 null。
/** * Returns the value to which the specified key is mapped, * or {@code null} if this map contains no mapping for the key. * * <p>More formally, if this map contains a mapping from a key * {@code k} to a value {@code v} such that {@code (key==null ? k==null : * key.equals(k))}, then this method returns {@code v}; otherwise * it returns {@code null}. (There can be at most one such mapping.) * * <p>A return value of {@code null} does not <i>necessarily</i> * indicate that the map contains no mapping for the key; it's also * possible that the map explicitly maps the key to {@code null}. * The {@link #containsKey containsKey} operation may be used to * distinguish these two cases. * * @see #put(Object, Object) */ public V get(Object key) { Node<K,V> e; return (e = getNode(hash(key), key)) == null ? null : e.value; } /** * Implements Map.get and related methods * * @param hash hash for key * @param key the key * @return the node, or null if none */ 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 && // 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; }
六、HashMap 的 remove 操作
源码走起:
/** * Removes the mapping for the specified key from this map if present. * * @param key key whose mapping is to be removed from the map * @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 remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value; } /** * Implements Map.remove and related methods * * @param hash hash for key * @param key the key * @param value the value to match if matchValue, else ignored * @param matchValue if true only remove if value is equal * @param movable if false do not move other nodes while removing * @return the node, or null if none */ 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; }
七、参考
Java8 中 HashMap 的相关基本操作源码介绍,这里也可以直接参考【Java7/8 中的 HashMap 和 ConcurrentHashMap 全解析】,介绍得还是挺详细的。
备注:关于红黑树和ConcurrentHashMap,有待后续的进一步研究。