直接从add方法开始,引入眼帘的为以下代码
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
看到这里的时候有点疑惑,map是什么时候做的初始化,PRESENT又是什么。
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
/**
* Constructs a new, empty set; the backing HashMap instance has
* default initial capacity (16) and load factor (0.75).
*/
public HashSet() {
map = new HashMap<>();
}
然后可以发现map是在HashSet的无参构造方法里面初始化的,PRESENT是一个static的Object常量。
继续回到add方法,点到map的put方法里面,看下具体实现。
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
这里的key就是我们add进来的值,而value是刚刚我们看到的Object常量,然后发现它调用的是putVal方法,其中第一个参数是hash(key),应该是用来计算hash值的,我们点进去看一下,
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
其中可以看到hash值进行了>>>16的运算,
当table的大小为64时:
0000 0000 0000 0000 0000 0000 0100 0000
n=table.length-1
0000 0000 0000 0000 0000 0000 0011 1111
hash:4242428
二进制:0000 0000 0100 0000 1011 1011 1111 1100
无符号右移16位:0000 0000 0000 0000 0000 0000 0100 0000
进行异或运算:0000 0000 0100 0000 1011 1011 1011 1100
假设hash:4242428没有无符号右移16位,则hash:4242428&n等于
hash:0000 0000 0100 0000 1011 1011 1111 1100
n:0000 0000 0000 0000 0000 0000 0011 1111
table下标:0000 0000 0000 0000 0000 0000 0011 1100
table下标:60
hash:252
二进制:0000 0000 0000 0000 0000 0000 1111 1100
则hash:252&n等于
hash:0000 0000 0000 0000 0000 0000 1111 1100
n:0000 0000 0000 0000 0000 0000 0011 1111
table下标:0000 0000 0000 0000 0000 0000 0011 1100
table下标:60
这里我们可以看到hash:4242428和hash:252两个值存放位置冲突了,
为什么相差这么大的两个数的存放位置会冲突呢,因为当table的length不够大时
hash&n只会运算到低位,而高位没有参与运算
所以无符号右移16位,再与原hash值进行异或运算的目的就是在table.length比较小的时候,
让高位也参与进运算,减少碰撞
回到putVal方法
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node[] tab; Node p; int n, i;
//初始化tab和n的值
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//如果tab[i]为空的话,直接存进去
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
//hash值相等且key相等,则判断是一样的
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//如果是树,则按照树结构添加数据
else if (p instanceof TreeNode)
e = ((TreeNode)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);
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;
}
/**
* 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[] resize() {
Node[] oldTab = table;
//old table的容量
int oldCap = (oldTab == null) ? 0 : oldTab.length;
//old table的门槛
int oldThr = threshold;
//初始化new table的容量和门槛
int newCap, newThr = 0;
//当oldCap > 0时,给newCap,newThr分别赋值为oldCap,oldThr的两倍
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
}
//当oldThr > 0时,newCap等于oldThr
else if (oldThr > 0)
newCap = oldThr;
//当oldCap和oldThr都不大于0时,直接初始化newCap,newThr
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
//oldCap > 0或者oldThr > 0时,newThr 有可能没有赋上值
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"})
//创建newTab
Node[] newTab = (Node[])new Node[newCap];
table = newTab;
//如果oldTab != null,则将值复制到newTab
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
//如果e.next == null,说明不是链结构
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
//如果e是一个TreeNode
else if (e instanceof TreeNode)
((TreeNode)e).split(this, newTab, j, oldCap);
//Node
else { // preserve order
Node loHead = null, loTail = null;
Node hiHead = null, hiTail = null;
Node 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;
}