public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
// 继承了AbstractMap类,实现了Cloneable和Serializable接口
// 一些主要的参数
//首先是默认的初始化容量,可以看到这里是1左移4位,即16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
// 最大容量为2的30次方
static final int MAXIMUM_CAPACITY = 1 << 30
// 负载因子0.75
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// 由链表转换为红黑树的阈值,这里可以看到是8
static final int TREEIFY_THRESHOLD = 8;
// 由红黑树转换为链表的阈值,这里可以看到是6
static final int UNTREEIFY_THRESHOLD = 6;
// 扩容的阈值,容量和负载因子的乘积
int threshold;
// 当链表的的长度大于8时,会判断容量是否大于64,如果大于64则转换成红黑树,小于64则先扩容
static final int MIN_TREEIFY_CAPACITY = 64;
// 哈希表,存储键值对
transient Node<K,V>[] table;
// 存储的元素个数
transient int size;
// 当HashMap里存储的值被改变时(增删),modCount加1,主要用来实现fail-fast机制
transient int modCount;
// 构造方法,可以自定义容量和负载因子
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; // all other fields defaulted
}
// Node节点的内部结构,可以看到这里是单向链表
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;
}
}
// hash方法,将key的hashcode的高16为与低16位进行异或运算
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
// 调用构造方法传入HashMap的容量时,根据传入的容量值来计算实际的容量值(大于传入值的最小2的n次方)
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;
}
// 返回当前元素个数
public int size() {
return size;
}
// 判断是否为空
public boolean isEmpty() {
return size == 0;
}
// get方法,获取key对应的value,底层调用getNode方法
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;
// 判断哈希表不为空且长度大于0,且对应下标的元素不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
// 如果头节点的key与要找的key相等,则返回头节点
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);
// 如果头节点不是树节点,则遍历链表,如果找到相等的key,返回对应的节点
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
// 没找到,返回null
return null;
}
// 判断是否包含某个key,底层调用的getNode方法
public boolean containsKey(Object key) {
return getNode(hash(key), key) != null;
}
// put方法,底层调用putVal方法
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;
// 如果哈希表为空或者长度等于0,则进行扩容操作
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
// 哈希表不为空,则根据根据hash和length找到对应的链表和二叉树,判断是否为空
if ((p = tab[i = (n - 1) & hash]) == null)
// 为空则直接将key和value以及对应的hash封装成一个Node对象,放到哈希表对应的位置
tab[i] = newNode(hash, key, value, null);
else {
// 如果不为空,则判断头节点的key和要put的键值对的key是否相等
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
// 相等则将头节点赋值给e
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,则尝试转化成红黑树(这里如果哈希表的长度小于64,则先扩容)
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
// 如果遍历的中途找到了相同的key,则跳出循环
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
// e不为空,则说明找到了key相同的节点,新值覆盖旧值,将旧值返回
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
// 没有找到key相同的节点,说明插入了新的节点,则将modCount加一
++modCount;
// 判断是否超过扩容的域指,超过则扩容
if (++size > threshold)
resize();
// 新增节点的后续工作
afterNodeInsertion(evict);
return null;
}
// 扩容方法
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
// 当前容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
// 当前扩容阈值
int oldThr = threshold;
// 新的容量和阈值,初始值为0
int newCap, newThr = 0;
// 如果当前容量大于0,判断是否为达到容量上限
if (oldCap > 0) {
// 如果达到上限,则将扩容阈值设置为Integer最大值(相当于不再扩容),返回旧的哈希表
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
}
// 如果当前容量等于0且扩容阈值大于0,则将新的容量设置为当前阈值
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
// 如果当前容量和扩容阈值都等于0,则将新的容量和扩容阈值都置为默认值
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"})
// 根据新的容量创建新的哈希表
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;
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;
}
// 尝试将链表转化成红黑树的方法
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
// 如果哈希表的长度小于设置阈值(64),则进行扩容操作
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);
}
}
// 删除某个key对应的键值对,底层调用removeNode方法
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;
// 判断哈希表不为空且要找的key对应的链表或者红黑树不为空
if ((tab = table) != null && (n = tab.length) > 0 &&
(p = tab[index = (n - 1) & hash]) != null) {
// 如果头节点的key和我们要找的key相等,则将头节点赋值给node
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 {
// 如果找到相等的key,则将对应的节点赋值给node
if (e.hash == hash &&
((k = e.key) == key ||
(key != null && key.equals(k)))) {
node = e;
break;
}
p = e;
} while ((e = e.next) != null);
// 注意:上面的循环结束后,p是e的上一个节点
}
}
// 如果node不为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);
// 如果是node是头节点
else if (node == p)
tab[index] = node.next;
// node是中间的某个节点
else
p.next = node.next;
// 收尾工作
++modCount;
--size;
afterNodeRemoval(node);
return node;
}
}
// 找不到返回null
return null;
}
以上是HashMap中一些常用的方法
一些问题:
1.hash()方法内为什么要将key的hashcode高16位与低16位进行运算?
首先我们知道当put某个键值对的时候,HashMap会先将key的hashcode调用hash方法,得到一个值hash,然后再将这个hash值与数组的length-1进行&操作,最终得到index,将该键值对放到对应index下标的链表或者红黑树上。
那么在由于我们使用HashMap时,一般HashMap的容量会处于一个范围,既不会太小也不会太大,那么就导length-1的范围也是绝大多数时候也是处在某一个范围内的,当hash值与length-1进行&操作时,会将这两个值的二进制进行&操作,那么当length-1处于这个范围时,二进制高16位基本都是0,那么hash的二进制高 16位在进行运算时无论是1还是0,最终&结果都是0,相当于高16位没有参与运算,这样就会大大增加哈希冲突的概率,所以我们这里先将hashcode的高16位与低16位进行一次运算,相当于间接让hashcode的高位参与了计算index的过程,也就减少了哈希冲突。
2.为什么HashMap的容量要为2的n次方?
当们确定一个key的index是,需要将key的hash与length-1进行一个取模运算,而这种运算有两种方式一种是直接计算余数即hash%length,还有另外一种则是用&运算,HashMap底层就是用的后者,但是只有当length为2的幂次方时,才有hash%length==hash&(length-1),这就是第一个原因。 其次当length为2的幂次方时,length-1的二进制低位都为1,这样就与hash进行&运算时,可以保留hash的低位,也就是说低位&运算的结果取决于hash值,而不会去取决于length,可以减少哈希冲突。(设想当length-1的某一位为0,则无论hash值为多少,最终此位结果都是0,也就是说index会一直取不到某些值,这就会导致哈希冲突增加)。
3.fail-fast
fail-fast机制表现在当HashMap在进行某些遍历操作时,如果里面的元素被增删了,则会抛出ConcurrentModificationException异常,比如说调用foreach方法进行遍历,或者用迭代器进行遍历时,底层会先将modCount变量赋值给一个exceptModCount变量,在遍历的过程中会判断这两个变量是否相等,如果相等则继续执行,如果不相等则抛出上面的异常,fast-fail机制主要是避免在HasMap在遍历过程中被修改。
4.HashMap1.7和1.8的区别
主要区别:
- 1.7底层的数据结构是数组和链表,1.8底层的数据结构是数组链表和红黑树,将链表转化成红黑树,避免在链表长过长时查询效率降低。
- 1.7采用的是头插法,1.8采用的是尾插法,当遍历完链表时如果找不到匹配的key,1.7将新的节点放在链表的头部,1.8则放在尾部,避免了多线程同时扩容时产生死链的问题。