Java中重写equals方法为什么要重写hashcode方法?
直接看下面的例子:
首先我们只重写equals()方法
public class Test { public static void main(String[] args) {
User user1 = new User();
User user2 = new User();
System.out.println(user1.equals(user2));
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
HashMap<User,String> map = new HashMap<User,String>();
map.put(user1,"123");
map.put(user2,"456");
System.out.println(map.get(user1));
System.out.println(map.get(user2));
} } class User{
private String name;
private String password;
private String address; @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name) &&
Objects.equals(password, user.password) &&
Objects.equals(address, user.address);
} }
输出结果:
true
1163157884
1956725890
123
456
有没有发现问题出在哪里?
用equals比较说明对象相同,但是在HashMap中却以不同的对象存储(没有重写hascode值,两个hascode值,在他看来就是两个对象)。
到底这两个对象相等不相等?
说明必须重写hashCode()的重要性,
接下来重写重写equals方法和hashCode方法,再比较
public class Test { public static void main(String[] args) {
User user1 = new User();
User user2 = new User();
System.out.println(user1.equals(user2));
System.out.println(user1.hashCode());
System.out.println(user2.hashCode());
HashMap<User,String> map = new HashMap<User,String>();
map.put(user1,"123");
map.put(user2,"456");
System.out.println(map.get(user1));
System.out.println(map.get(user2));
} } class User{
private String name;
private String password;
private String address; @Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name) &&
Objects.equals(password, user.password) &&
Objects.equals(address, user.address);
} @Override
public int hashCode() {
return Objects.hash(name, password, address);
}
}
输出结果:
true
29791 //相同的对象
29791
456 //说明以一个值key存储,相同的值
456
看到这里,你懂了吗? 还不懂,可以自己实现一遍代码。