常见问题:
HashMap为啥线程不安全
无hash冲突时,通过hash判断出对应位置为null,和在null位置new node时会线程不安全
在扩容时,++size,和比较size和阈值时会线程不安全
HashMap是如何处理哈希碰撞的
拉链法
HashMap是如何get元素的
先找hash,再找key
HashMap的长度为什么是2的幂次方
为保证 length % hash == (n - 1) & hash,提高性能
HashMap中的key用哪些数据类型好
用String、Integer好。因为都是final型,不可变,有较高性能,且不容易出错。
如果使用别的数据类型,要记得重写hashcode和equals方法。
模拟hash桶的put操作:
HashMap的put(key)流程图
demo1
public static void main(String[] args) {
Map<Integer,Integer> map = new HashMap<>(); // 初始化
for (int i=0; i<=1000; i++) {
map.put(i,i); // 添加元素
}
System.out.println(map.get(11)); // 获取元素
}
demo2
public static void main(String[] args) {
HashMap<Integer,Integer> map = new HashMap<>(); // 初始化
for(int i=0;i<=70;i++){
map.put(5+16*i,5+16*i); // 模拟hash碰撞
}
System.out.println(map);
}
常量:
//默认初始容量16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
//最大容量:2的30次方(4字节,1个字节8位,32位,个位是2的0次,最高位符号位,最高位下一位是2的30次)
static final int MAXIMUM_CAPACITY = 1 << 30;
//默认加载因子
static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树形阈值(链表长度达到8尝试转为树)
static final int TREEIFY_THRESHOLD = 8;
//非树型阈值(树元素个数小于6尝试转回链表)
static final int UNTREEIFY_THRESHOLD = 6;
//最小树容量(size大于等于64时,链表才可能转为红黑树,否则走扩容)
static final int MIN_TREEIFY_CAPACITY = 64;
属性:
//node数组
transient Node<K,V>[] table;
//entrySet
transient Set<Map.Entry<K,V>> entrySet;
//size
transient int size;
//modCount
transient int modCount;
//门槛
int threshold;
//负载因子
final float loadFactor;
//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;
}
}
new():
//负载因子初始化为0.75
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
new(int initialCapacity):
//负载因子初始化为0.75,阈值初始化为满足指定容量的最小2次方
public HashMap(int initialCapacity) {
//指定容量,加载因子默认0.75
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
//根据指定容量和加载因子实例化
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的次方
this.threshold = tableSizeFor(initialCapacity);
}
//计算满足指定容量的最小2次方
static final int tableSizeFor(int cap) {
//先减1计算容量时再补1(此处为了求合理的容量需要如此计算)
int n = cap - 1;
//n与n右移1位执行|运算(此时最高位一定为1,右移一位做|保证前俩位(如果有俩位)都为1)
n |= n >>> 1;
//n与n右移2位执行|运算(此时前俩位一定都为1,右移俩位做|保证前四位(如果有四位)都为1)
n |= n >>> 2;
//n与n右移4位执行|运算(此时前四位一定都为1,右移四位做|保证前八位(如果有八位)都为1)
n |= n >>> 4;
//n与n右移8位执行|运算(此时前八位一定都为1,右移八位做|保证前十六位(如果有十六位)都为1)
n |= n >>> 8;
//n与n右移16位执行|运算(此时前十六位一定都为1,右移十六位做|保证三十二位(如果有三十二位)都为1)
n |= n >>> 16;
//不为负且没达到最大容量则+1,结果为2的k次方
return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
}
put():
//put
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//hash
//右移16位是为了同时保留高16位和低16位的特征
//异或是为了更好的保留各部分的特征(&的结果会趋向于0,|的结果会趋向于1)
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
//putVal
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
//初始化长度为16
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//若hash位置为null,则不存在hash冲突
//(若n=16,则n-1=15=1111,(n - 1) & hash相当于保留n-1范围内的值)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
//hash冲突
else {
Node<K,V> e; K k;
//key相同,替换
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);
//若key不相同且不为树,则以链表形式追加到尾部
else {
//遍历链表
for (int binCount = 0; ; ++binCount) {
//若遍历到尾部,则链表尾部追加元素及相关操作后跳出循环
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
//若链表尾部追加元素后长度达到8,则尝试调整为红黑树
if (binCount >= TREEIFY_THRESHOLD - 1)
//尝试调整为红黑树(若node数组长度小于64依然走扩容)
treeifyBin(tab, hash);
break;
}
//若遍历到与新加元素key相等的元素,则覆盖后跳出循环
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;
//size+1>阈值时,调整node数组长度
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
//调整node数组长度
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
//扩容为2倍,扩容阈值也变为2倍
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;
//初始化容量为16,阈值为16*0.75=12,返回长度为16的node数组
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;
//node数组复制,长度改变为新容量
if (oldTab != null) {
//遍历node数组各node
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
//若node为null直接跳过,不为空才处理
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//若node没有next,只需要把node上唯一元素按照新hash算法copy到新node数组里
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//若node为树节点,则按照树节点处理方式copy过去
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
//否则该节点为链表,则按照链表节点处理方式copy过去
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;
}
//尝试调整为红黑树(若node数组长度小于64依然走扩容)
final void treeifyBin(Node<K,V>[] tab, int hash) {
int n, index; Node<K,V> e;
//若node数组为null或者node数组长度小于64,走扩容
if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
resize();
//只有当node数组长度大于等于64,才转为红黑树
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);
}
}
get():
//get
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
//先根据key的hash定位,再根据key定位
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;
}