一、概述:
由前面的博客可知,当HashSet的泛型为自定义类(如Student)时,虽然我们重写了hashCode方法,但是并未重写equals方法,因此具有重复属性的对象依然会存储成功,本博客继续讨论重写了equals方法之后的情况:
二、代码分析:
1.在Student类中重写hashCode方法的基础上我们继续重写equals方法:
package com.practice;
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {//obj值集合中的某个对象,因为集合中可能存的未必都是学生类,比如集合泛型为Object的时候,既可以存学生对象,还可以存其它对象
if(obj instanceof Student ){
Student stu = (Student)obj;
return this.id.equals(stu.id);//this即是当前正在试图被存储的对象
}
return false;
}
@Override
public int hashCode() {
return id.hashCode();
}
}
2.再执行向泛型为Student的HashSet中添加具有相同id的对象的操作:
package com.practice;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<Student>();
set.add(new Student("123"));
System.out.println(set.add(new Student("123")));//此处输出为false,由此证明了重写equals方法和hashCode方法成功避免了添加具有相同id的对象时会成功的现象
}
}
3.add方法的底层代码为:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
4.put方法的底层代码为:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
5.put方法中的hash方法如下,由于已经重写了hashCode方法,所以两次存储时的hash值相同;
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
6.put方法中的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全局变量已经有值了,所以tab不为空 tab.length不等于0,所以该if为false n为 16
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)// i = (n - 1) & hash (数组长度-1)& hash 的值,即(16-1) & hash,因为第一个和第二个值的hash方法返回值相同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是一样的 ,所以存第二个对象时tab[i = (n - 1) & hash]不为null p变量存储的是集合中已有元素
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))))// p.hash == hash true (k = p.key) == key false (key != null && key.equals(k)) 因为学生类重写equals,所以调用Student类中equals 比较的是两个对象id是否相同 true
e = p;//将p指定的集合中元素赋值给e变量
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)// onlyIfAbsent本来就为false,所以!onlyIfAbsent true
e.value = value;//value变量其实是第二次存储对象时存入的值 Object
afterNodeAccess(e);
return oldValue;//返回第一个学生对象,存储失败
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
总结:当HashSet的泛型为自定义类时,只有我们在自定义类中重写了equals方法和HashCode方法后,我们才能避免添加具有相同属性的对象时会添加成功的现象。