一、HashMap中hash方法和HashSet中add方法执行过程分析
在我之前的“HashSet中add方法的执行过程”博客中对于hash方法和add方法均进行了较为详细的过程分析,所以此处不再赘述,如不了解的可以参考上述博客,如下将会介绍HashSet中add方法存储自定义类型对象的特点是什么
二、HashSet中add方法存储自定义类型对象
首先展现的是需要的自定义类Student代码
class Student{
String id;
public Student(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
//这里重写的equals方法是为了说明id值相同即是同一Student对象
if (obj instanceof Student) {
//应注意到其中应用了instancof关键字:instanceof运算符用于判断该运算符前面引用类型变量指向的对象是否是后面类,或者其子类、接口实现类创建的对象;此处的作用是判断所添加的对象obj是否是学生类(有可能是Dog类等其他类)
Student student = (Student) obj;
return id.equals(student.id);
}
return false;
}
@Override
public int hashCode() {
//这里重写了Object类中的hashCode方法,如果不重写则hashcode方法接受的值是输入对象的地址值,而不是输入对象的id值,重写后则接受的就是输入对象的id值了,这是存储自定义类的重大不同之处
return id.hashCode();
}
}
这里还是需要展示一下从add方法追溯到的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 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;
}
如下是测试代码
HashSet<Student> set = new HashSet<>();
//——>HashSet无参构造方法——>HashMap无参构造方法——>HashMap table为null
set.add(new Student("1"));
//tab = resize()——>resize()为table变量赋值,该值即使该方法返回值——>tab布局变量与table全局变量指向一个数组,数组长度是16
//并且由于Student类中重写了Object类中的hashCode方法,则上述putVal方法中使用的hash值则是由Student类中的id值计算得来的,则往后的执行过程实际上就是添加数据是String类型时的执行过程了,这点在我之前的博客《HashSet中add方法的执行过程》中就有详细介绍,此处就可以省略了
set.add(new Student("1"));
set.add(new Student("2"));