自定义对象重写equals的一些规范
自定义的对象作为key值,最好同时重写hashCode和equals方法
原因可查看哈希函数实现原理(一)
规范 :
- 自反性:对于非空的对象o, o.equals(o)必须返回true;
- 对称性:对于非空的对象a,b,如果a.equals(b) 返回true,那么b.equals(a)也必须返回true;
- 传递性:对于非空的对象a,b,c,如果a.equals(b)、b.equals( c ),那么a.equals( c )也必须返回true
- 对于非空的对象a,b,只要对象所用的信息没有被修改,那么多次调用的结果返回必须是一致的。
- 对于非空的对象o,o.equals(null)必须返回false
假设有一个学生Student类,判断条件为如果他们的姓名和年龄都相等就判定他们相等
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
// if(o == null || o.getClass() != getClass()) return false;
Student student = (Student) o;
// return age == student.age &&
// Objects.equals(name, student.name);
//字符串可能为空的情况
return age == student.age && (student.name == null ? name == null : student.name.equals(name));
}