- HashMap源码解析_jdk1.8(二)
- 构造函数
- put方法
- resize扩容方法
HashMap源码解析_jdk1.8(二)
构造函数
HashMap提供了如下几个构造函数:
/*** 构造一个具有指定初始容量和负载因子的空HashMap.** @param initialCapacity 初始容量* @param loadFactor 负载因子* @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;// 如果用户通过构造函数指定了一个数字作为容量,那么Hash会选择大于该数字的第一个2的幂作为容量。(1->1、7->8、9->16)this.threshold = tableSizeFor(initialCapacity);
}/*** 构造一个具有指定初始容量和默认负载因子(0.75)的空HashMap.** @param initialCapacity 初始容量* @throws IllegalArgumentException if the initial capacity is negative.*/
public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);
}/*** 构造一个具有默认初始容量(16)和默认负载因子(0.75)的空HashMap.*/
public HashMap() {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) {this.loadFactor = DEFAULT_LOAD_FACTOR;putMapEntries(m, false);
}
如果用户通过构造函数指定了一个数字作为容量,那么Hash会选择大于该数字的第一个2的幂作为容量。(1->1、7->8、9->16)
/*** Returns a power of two size for the given target capacity.*/
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;
}
从构造函数我们可以看出,在常规构造器中,没有为数组table分配内存空间(有一个入参为指定Map的构造器例外),而是在执行put操作的时候才真正构建table数组。
put方法
/*** 将指定的value与该map中的指定key相关联.* 如果map中已经包含指定key,key对应的value将会被新值覆盖** @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) {// 根据key计算hash值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* @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为null或长度为0,为数组table分配内存空间if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;// 判断插入的位置是否是冲突的,如果不冲突就直接newNode,插入到数组中即可if ((p = tab[i = (n - 1) & hash]) == null)tab[i] = newNode(hash, key, value, null);else { // 如果插入的hash值冲突了Node<K,V> e; K k;// 判断table[i]中的元素是否与插入的key一样,若相同那就直接使用插入的值p替换掉旧的值e。if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))e = p;// 判断插入的数据结构是红黑树还是链表,在这里表示如果是红黑树,那就直接putTreeVal到红黑树中else if (p instanceof TreeNode)e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);// 数据结构是链表else {// 遍历table数组是否存在for (int binCount = 0; ; ++binCount) {// 不存在直接newNode(hash, key, value, null)if ((e = p.next) == null) {p.next = newNode(hash, key, value, null);// 判断当前链表的长度是否大于阈值8,如果大于那就会把当前链表转变成红黑树if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}// 如果存在了跳出循环if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}// 如果存在了,直接使用新的value替换掉旧的valueif (e != null) { // existing mapping for keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;// 插入成功,判断是否需要扩容if (++size > threshold)resize();afterNodeInsertion(evict);return null;
}
resize扩容方法
/*** table数组初始化或长度加倍. 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;// 扩容前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)// 将阈值扩大为2倍newThr = oldThr << 1; // double threshold}// 阈值已经初始化了,就直接使用else if (oldThr > 0) // initial capacity was placed in thresholdnewCap = oldThr;else { // zero initial threshold signifies using defaults// 没有初始化阈值那就初始化一个默认的容量和阈值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"})// 新建一个数组长度为原来2倍的数组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// 如果是多个节点的链表,将原链表拆分为两个链表Node<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;// 扩容后,若hash值新增参与运算的位=0,那么元素在扩容后的位置=原始位置if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}// 扩容后,若hash值新增参与运算的位=1,那么元素在扩容后的位置=原始位置+oldCapelse {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);// 链表1存于原索引if (loTail != null) {loTail.next = null;newTab[j] = loHead;}// 链表2存于原索引加上原hash桶长度的偏移量if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab;
}
参考:
https://zhuanlan.zhihu.com/p/79219960
https://www.cnblogs.com/theRhyme/p/9404082.html#_lab2_1_1