重写equals()以及hashCode()
1.使用IDEA工具自动重写User.java中的equals()
和hashCode()
或在User.java中添加如下代码:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(gender, user.gender) &&
Objects.equals(birthday, user.birthday);
}
@Override
public int hashCode() {
return Objects.hash(id, name, gender, age, birthday);
}
2.在UserDao.java中测试equals()
方法和hashCode()
方法
public static void main(String[] args) {
User u1 = new User();
u1.setId(1814010924);
u1.setName("sxz");
u1.setGender("男");
User u2 = new User();
u2.setId(1814010924);
u2.setName("sxz");
u2.setGender("男");
System.out.println("== :"+ ( u1==u2 ));
System.out.println("equals :" + u1.equals(u2));
System.out.println("hashCode :" + ( u1.hashCode()==u2.hashCode() ));
}
3.测试结果: