新建一个Student类,重写equals()方法和hashCode()方法
class Student {
String name;
int ID;
public Student() {}
public Student(String name, int ID) {
this.name = name;
this.ID = ID;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return ID == student.ID && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, ID);
}
}
equals()方法解读
@Override
public boolean equals(Object o) {
if (this == o) return true;//若地址相同,则返回true
if (o == null || getClass() != o.getClass()) return false;//若带比较的对象为null,或者两者所属的类不同,则返回false
Student student = (Student) o;//能到这一步,说明(Object o)的类型为Student,则将o进行类型转换成Student
return ID == student.ID && Objects.equals(name, student.name);//若ID相等且name相等,则返回true
}
这里要注意两个问题
1.第4行中对于o==null的判断
Student s1 = new Student();//s1==null为false,因为new的时候创建了对象,有对应的内存地址
Student s2 = null;//s2==null为true,因为没有实例化Student,所以没有内存地址
2.出现了一个 Objects.equals(name, student.name)方法,该方法的源码如下
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));//若a与b的内存地址相同则直接返回true;否则,若a不为null且a equals b,返回true
}
hashCode()方法解读
@Override
public int hashCode() {
return Objects.hash(name, ID);
}
Objects.hash(name, ID)方法的源码如下
public static int hash(Object... values) {
return Arrays.hashCode(values);
}
Arrays.hashCode(values)方法的源码如下
public static int hashCode(Object a[]) {
if (a == null)
return 0;
int result = 1;
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}