add方法
add方法,向HashSet集合中添加元素。
我们先看一段代码。
package add;
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Object> list=new HashSet<>();
String name="Tom";
list.add(name);
}
}
显而易见,我们创建了泛型为Object类型的list集合,并添加了字符串类型的元素“Tom”。
我们对add方法按ctrl键,查看add方法的底层源代码,结果如下——
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
我们可以看出,e就是我们传入的name,而E指代e 的数据类型,类似于方法传参时的(int a)。
我们传入e,但是还调用了map接口的put方法——
put(K key, V value) 将键(key)/值(value)映射存放到Map集合中
我们知道,在HashMap中key即键是不能重复的,否则覆盖已有的key对相应的值 。
所以HashSet添加的元素也不允许重复。显然key就是我们输入的值,value是add方法之中默认的PRESENT,因为是大写字母,显然是个常量。
继续分析,add方法返回的是一个boolean类型的值,map调用了put方法,其中e是key,而value被设置成了常量。
这行代码的意思是,如果put方法的返回值为null,那么就返回true。
我们继续点开HashMap中的put方法,得到代码——
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
返回的是一个putVal方法,并且初始设定了hash(key), key, value, false, true五个值,其中hash()方法是对key求哈希码。
我们点开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;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
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);
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 mapp