我们知道,add方法可以用来向集合中添加元素,对于HashSet集合来说,不允许存储重复的元素,当我们存储元素的时候,集合会对添加进来的元素进行判断是否重复,首先我们对新加元素进行分析:
add方法源码:(jdk-11.0.4)
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
此时我们发现,返回值是一个布尔值,如果添加成功,则返回true,否则返回false,那么其中用到了put方法,其属于HashMap集合,用来将元素添加到HashMap中的Key,而我们知道,HashMap集合是Key和value一一对应的关系,也就是说key不允许重复,而此时显然我们不需要添加value,此时的value值是一个Object常量,put方法源码如下
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
此时其中用到了putVal和hash()方法:
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)//table=null,tab=null,则(tab=table)==null为true
n = (tab = resize()).length;//resize()方法直接为table返回newTab,resize()方法也返回newTab,所以,table和tab是一个对象,数组长度16
if ((p = tab[i = (n - 1) & hash]) == null)//i = (n - 1) & hash 数组长度-1 & hash i是下表 tab[i -(n-1) & hash],因为此时只存储一个值,所以一定是null
tab[i] = newNode(hash, key, value, null);//tab[i] i (n-1) & hash 为(n-1)&hash添加一个元素,因为数组是地址传递,所以table全局变量i也有值
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);
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;
}
hash()方法
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
resize()方法:
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = 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)
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;
@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;
}
也就是说,当我们添加一个不存在的元素时, 首先调用HashSet类中的add方法,实质上是通过HashMap类型的全局变量map调用put方法。紧接着put方法调用putVal方法,执行putVal方法,table是一个全局变量,创建对象时并没有给table赋值,因此,tab = table = null,执行第一个if语句,调用resize方法。另tab等于resize方法的返回值。
在resize方法中,给全局变量table赋值为newTab,newTab初始数组长度为16,并且返回值也为newTab。又因为tab等于resize方法的返回值,所以第一个if语句执行结束后table和tab指向同一个地址,n = 16。
执行第二个if语句,第二个if语句的判断条件是将hash值与(n-1)做按位与运算,动态的找到数组的一个元素,判断是否为null。因为并未给数组tab赋值数组里的元素一定都为null,所以if语句的判断条件一定成立。if语句 tab[i] = newNode(hash, key, value, null);将传入的结点赋值给在if语句判断条件里找到的那个数组元素。
执行第三个也是最后一个if语句,返回null。因为putVal返回值为null,null = null,所以put方法的返回值为true,即add方法的返回值为true,添加成功。