上接HashSet中的add()方法( 二 )(详尽版)
,前两篇说的是泛型为String类的add()方法的具体执行过程,此后三篇说说泛型为自定义类的add()方法的具体执行过程:
首先让我们来自定义一个学生类:
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
}
我们通过Test类来具体实现学生类:
import java.util.HashSet;
public class Test {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<Student>();//泛型为Student
set.add(new Student("100"));//当执行该行时,由于是第一次存值,与String类无异,所以这里就不再赘述了
set.add(new Student("100"));//我们直接从再次存值讲起
}
}
调用HashSet中的add()方法:
我们知道add()方法是有返回值的,若key一样,返回false,即添加失败;若key不一样,返回true,即添加成功
public boolean add(E e) {
return map.put(e, PRESENT)==null;//e即为add()方法中的参数(此时即为第二个创建的对象的"100"),value为常量PERSENT(Object类型)
}
//从代码中可以看出,若put返回null,则add返回true,若put不返回null,则add返回false,那put()方法是怎么返回一个值的呢?让我们接着往下看:
接着调用HashMap中的put()方法:
public V put(K key, V value) {//key也是add()方法中的参数
return putVal(hash(key), key, value, false, true);//此时先调用hash()方法,我们在(一)篇分析过了,它会返回一个int类型的值
//而且在(零)篇中我们分析过,若泛型是自定义类类型(未重写equals()方法),
//则返回的hash值是不同的(因为这两次的地址是不同的)
}
//此处就是将put()方法转交给putVal()方法,让putVal()来完成:返回一个值(null或!null)
再调用HashMap中的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)//因为table中已存入了一个值,所以table不为null,tab也不为null,所以tab.length也不为0
//所以该if语句的条件不满足,直接跳到下一个if语句
n = (tab = resize()).length;
//因为未执行上一行,所以数组未进行初始化,所以数组仍是第一次存值时的数组,所以长度相同,即n不变
if ((p = tab[i = (n - 1) & hash]) == null)//我们知道tab是一个数组,i是索引,而此时n值不变,hash值与第一次的hash值不同,
//所以tab[i] == null 成立,所以执行下一行
tab[i] = newNode(hash, key, value, null);//为tab[i]赋值,此时newNode中的key、value、hash即为第二次add()中的参数,及对应的value(常量)、和hash值
//因为if语句已执行,所以此else语句不执行
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;
}
最后几行代码我们也不需要具体分析,我们关注的是最后一行代码:return null;
会返回null,
我们上面提到,putVal返回null也就相当于put()返回null,所以add返回true,添加成功!
但我们知道学生的id号是唯一的、不可重复的,所以可以尝试一下重写hashCode()方法来试试:
我们接着看HashSet中的add()方法( 四 )(详尽版)