面试问候语 — HashMap
HashMap简直就像问候语一样,面试官问一个HashMap,应聘者呢回答一下表示相互的尊敬。
-
散列表
我觉得说HashMap之前应该先说一下散列表(hash table)。散列表在进行插入,删除,查找的效率都是很高的,不考虑哈希冲突的情况下,仅需一次定位即可完成,时间复杂度为O(1)。对于散列表来说,确定元素的位置,就类似于在一个数组力通过下标确定元素一样。只不过散列表的 “下标” 是通过一定的算法来计算得出在散列表中称之为散列码(hash code)。 -
桶
java中,哈希表是用链表数组实现的,每一个列表被称之为桶(bucket)。想要查找表中对应对象的位置,就要先计算散列码,然后与桶的总数取余,所得到的结果就是保存这个元素的桶的索引。
当插入新的对象时,使用同样的计算方法计算出待插入对象应该保存的桶的索引,假如当前桶刚好是空的,则直接插入到桶中即可,当然也有可能桶已经满了,这种现象叫散列冲突,这是,需要用新的对象与铜钟的所有对象进行比较,啥看这个对象是不是已经存在。(JAVA SE8中,桶满的时候会将桶从链表转换为平衡二叉树。)
通常将桶数设定为预计元素总数的 75%-150% ,并且最好将桶的个数设置为一个素数,以防止键的聚集,标准类库中使用的是桶数是2的幂,默认值为16(为表大小提供的任何值都将被自动的转换为2的下一个幂)
当无法估计的存书的元素总数的时候,就有可能造成预估的值太小,如果散列表太满,就需要再散列(rehashed),如果要进行再散列就需要创建一个桶的数量更多的表,并且将所有元素重新插入到这个表中,然后丢弃原有的表。装填因子(load factor)就决定了何时对散列表进行再散列。一般默认值为0.75,即表中的75%的位置已经填满了元素,这个表就会用双倍的桶数来进行再散列。 -
HashMap
HashMap 由数组+链表组成的(JDK 1.8 中引入了红黑树,底层数据结构由数组+链表变为了数组+链表+红黑树),数组是HashMap的主体,链表则是主要为了解决哈希冲突而存在的,如果定位到的数组位置不含链表(当前entry的next指向null),那么对于查找,添加等操作很快,仅需一次寻址即可;如果定位到的数组包含链表,对于添加操作,其时间复杂度为O(n),首先遍历链表,存在即覆盖,否则新增;对于查找操作来讲,仍需遍历链表,然后通过key对象的equals方法逐一比对查找。所以,性能考虑,HashMap中的链表出现越少,性能才会越好。
hashMap中的基本存储结构为一个Node 数组,Node结构源码如下:
/**
* 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;
/**
* 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;
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;
}
}
Node 为HashMap中的一个内部类实现了Entry<K,V>接口。也可以理解为Node就是一个Entry。HashMap中的key-value都是存储在Node数组table中的。
还有一些需要关注的参数:
/**
* The default initial capacity - MUST be a power of two.
* 默认初始化的容量为16,必须是2的幂。 1 << 4 运算的结果就是16 即默认值为 16
*/
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.
* 初始化的最大值 1 << 30 计算结果为 1073741824
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* The load factor used when none specified in constructor.
* 默认的装载因子是0.75
*/
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.
* 一个桶(bucket)中的数据结构由链表转换成树的阈值。
* 即当桶中bin的数量超过TREEIFY_THRESHOLD时使用树来代替链表。默认值是8
*/
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.
* 当执行resize操作时,桶中的数据结构由树变成链表的阀值,
* 当桶中bin的数量少于UNTREEIFY_THRESHOLD时使用链表来代替树。默认值是6
*/
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.
* 当哈希表中的容量大于这个值时,表中的桶才能进行树形化
* 否则桶内元素太多时会扩容,而不是树形化
* 为了避免进行扩容、树形化选择的冲突,这个值不能小于 4 * TREEIFY_THRESHOLD
*/
static final int MIN_TREEIFY_CAPACITY = 64;
除了这些默认参数之外还有两个很特殊的参数
/**
* The next size value at which to resize (capacity * load factor).
* 当前HashMap的容量阀值,超过则需要扩容
* @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;
阅读源码可以发现当创建HashMap时调用了构造函数:
/**
* 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;
this.threshold = tableSizeFor(initialCapacity);
}
时,最终的结果并不是简单的又注释中所说的(capacity * load factor)而是调用了方法tableSizeFor(int cap),这方法全是位运算,其实转化为二进制然后详细看一下也能看懂个大概
,与之相似的还有HashMap的hashCode()方法和计算桶的位置时的取余。
/**
* Returns a power of two size for the given target capacity.
* 根据传入的数字,返回一个与之对应值的下一个2的幂
*/
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;
}
装载因子这个参数影响到了整个HashMap中桶的数量,桶数设定为预计元素总数的 75%-150%。所以说在预定元素总数不变的情况下,并且容量没到扩容阀值的情况下,负载因子增大,能容纳的元素增多,每个桶分得的元素就增多,冲突的几率增大,插入和查找的效率都降低,反之,负载因子减小,能容纳的元素减少,每个桶分得的元素就较少,冲突的概率减小,插入和查找的效率都提高。所以装载因子关系到整个HashMap的效率,默认值应该是一个折中的选择。
简单读一个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
* @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为空或者长度为0则初始化table
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果当前table节点,即当前元素应该保存的桶是空的则创建一个新的节点保存元素
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);
//如果当前桶中的元素大于TREEIFY_THRESHOLD 则将其转化为一个树
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
//如果找到相同元素则直接跳过逻辑
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
//如果存在则继续后续逻辑
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;
}
其中有一个很值得注意的参数modCount。
/**
* 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).
*/
transient int modCount;
从注释可以看出这个参数是用于保存不同的将会影响到整个HashMap的结构的或者可能影响到其中元素大小的操作次数。用于在内部遍历方法中监控迭代过程中,被操作的情况。当在迭代器初始化完成获取到当时的modCount作为预期值之后,modCount在变脸过程中被改变,导致预期值与当前值不相等时会抛出异常 ConcurrentModificationException,之前在迭代器中遇到过这个问题。
- 为什么容量为必须为2的幂
回到源码分析的put(K key, V value)方法中:
其中的实现里面有一个很有意思的位运算 (n - 1) & hash 而 n = tab.length 也就是桶的个数。
hash 则为新元素的散列码,之前说过在插入逻辑中需要先定位到桶的位置,而方式是取余。没错这里的 (n - 1) & hash就是一个取余的操作,都将其作为二进制码进行运算,因为n均为2的幂则其二进制数(忽略符号位)一定是以1 开头 ,后面都是0的结构,减去1之后则变成了0开头后面均为1的结构,此时与操作只会将相对应的位上同为1的数据保留下来,为0的数据都为0。取余的思维是被除数中包含N个除数之后,多余的数。在这里hash转化为二进制之后其超出二进制n-1的高位的部分肯定是2的n的倍数,所以超出的部分可以不做考虑,只需要考虑位数相同的部分而与操作之后,确定下来的肯定就是其不能达到n的那一部分数这一部分就是余数。
- hashCodede 的计算 :
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
可以看到散列码的计算是直接调用的Object.hashCode()生成了最初的一个hashCode,之后再将其与本身取无符号右移16位之后的值异或计算。所得的最终值作为hashCode。这样的做法更大程度的避免极端情况下的hashCode冲突:
引用 https://blog.csdn.net/qq_38182963/article/details/78940047
假设有一种情况,对象 A 的 hashCode 为 1000010001110001000001111000000,对象 B 的 hashCode 为 0111011100111000101000010100000。
如果数组长度是16,也就是 15 与运算这两个数, 你会发现结果都是0。这样的散列结果太让人失望了。很明显不是一个好的散列算法。
但是如果我们将 hashCode 值右移 16 位,也就是取 int 类型的一半,刚好将该二进制数对半切开。并且使用位异或运算(如果两个数对应的位置相反,则结果为1,反之为0),这样的话,就能避免我们上面的情况的发生。
总的来说,使用位移 16 位和 异或 就是防止这种极端情况。但是,该方法在一些极端情况下还是有问题,比如:10000000000000000000000000 和 1000000000100000000000000 这两个数,如果数组长度是16,那么即使右移16位,在异或,hash 值还是会重复。但是为了性能,对这种极端情况,JDK 的作者选择了性能。毕竟这是少数情况,为了这种情况去增加 hash 时间,性价比不高。
- equls 方法
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;
}
/*Object.equals*/
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public boolean equals(Object obj) {
return (this == obj);
}
方法中的逻辑很简单。在HashMap中判断元素是否相当或者元素是否存在的时 首先比较的时hashCode,当hashCode相等的时候说名元素存放在同一个桶中,此时需要与每一个元素进行比较的时候,时直接通过比较key和Value在内存中的的地址。hashCode相等并不代表元素就相等。hashCode取决于对象中的hashCode方法如何生成hashCode,就Object而言也就如此:
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
* <p>
* The general contract of {@code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {@code hashCode} method
* must consistently return the same integer, provided no information
* used in {@code equals} comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
* <li>If two objects are equal according to the {@code equals(Object)}
* method, then calling the {@code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {@link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {@code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {@code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
*
* @return a hash code value for this object.
* @see java.lang.Object#equals(java.lang.Object)
* @see java.lang.System#identityHashCode
*/
public native int hashCode();
- HashMap扩容机制:
核心关注putVal方法,其中有一个对整个hashMap进行扩容 还有一个是对拉链法中产生的链表进行扩容或者说是转化为树的形式。
首先关注这个判断:
这里面有一个table,table定义和注释如下if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length;
可见是一个Node数组,Node是hashMap里面用于保存数据的结点。/** * 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;
可以看到上面的那个判断条件是初始化的时候,数据为空的时候会运行这个resize 方法。其实只是初始化,并不能说是一个扩容的操作。
再看一个判断:
这个判断是一个应该对于这里的讨论最适当的,size是当前这个HashMap的大小,后面的threshold是当前的阀值,默认初始化的时候为if (++size > threshold) resize();
DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY
再看一个判断:
这里就可以看到先判断了当前的元素总量是不是超过了最大限制 也就是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 } else if (oldThr > 0) // initial capacity was placed in threshold newCap = 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;
MAXIMUM_CAPACITY
这是极端情况下 当正常情况下,应该注意的是
这两个操作,通过位运算将阀值扩大了两倍同时新的桶数组的大小扩大两倍。//判断中进行的一个赋值: newCap = oldCap << 1 ... newThr = oldThr << 1; ... threshold = newThr;
从链表扩转为树的阀值为默认值8。
判断是
无论是扩容还是转化为树都是先添加结点,之后在运行相应的处理,判断都是在先加入了结点之后。if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash);