在写实验利用HashSet.contains进行判断当前对象在集合中是否存在的时候,需要判断该对象的hash值是否存在。这个时候需要override对象的hashCode方法。
假设对象所在的类大致如下:
public class Course {
private long ID;
private String name;
private String teacherName;
private String location;
private long Class_hours;
}
我们需要根据这些属性的值生成hash值。只有当这些属性的值相等的时候散列值相等,可以采用object.hash方法。
如下
public class Course {
private long ID;
private String name;
private String teacherName;
private String location;
private long Class_hours;
@Override
public int hashCode() {
return Objects.hash(ID, name, teacherName, location Class_hours);
}
}