上接 HashSet中的add()方法( 三 )(详尽版)
,我们重写一下Student类中的hashCode()方法来看看是否还能不能添加重复的学号了,
在学生类中重写hashCode()方法:
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
@Override
public int hashCode() {
return id.hashCode();//返回id的hashCode值
}
}
我们通过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"));
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类型的值
//而此时hash()方法中调用的是Student类中重写的hashCode()方法,此hashCode()方法返回上一个id的hashCode值,
//所以最终第二次存值的hash值与第一次的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)//此时n值不变,hash值也与第一次的hash值相同,
//所以tab[i]==null 不成立,所以该if语句条件不满足,下一行代码不执行
tab[i] = newNode(hash, key, value, null);
//因为if语句未执行,所以执行此else语句
else {
Node<K,V> e; K k;
if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
//由上一个if语句可知p是第一个存入的元素,所以此处p.hash指第一个存入元素的hash值,而hash是指该试图存入元素的hash值,很显然p.hash == hash为true
//k=p.key就是指第一个存入元素,显然(k = p.key) == key为false(因为两者的地址不同)
//k != null显然为true
//key.equals(k)为false,因为Student类未重写equals()方法,调用的还是Object类中的equals()方法,其比较的是地址,而两者地址不同
//所以该if语句条件不满足,不执行
e = p;
else if (p instanceof TreeNode)//显然,p不属于TreeNode
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {//执行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;
}
经过以上分析,我们知道若只重写hashCode()方法,还是可以存进去相同的id号
但学生的id号是唯一的、不可重复的,所以我们再来试试在重写hashCode()方法的基础上再重写一下equals()方法来:
我们接着看HashSet中的add()方法( 五 )(详尽版)