hashCode() & equals() 方法使用场景

it2023-02-04  53

 

案例一

没有重写hashCode 和equals()

public class User { private String userName; private Integer age; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } public class Main { public static void main(String[] args) { HashSet<User> set = new HashSet<>(); User user = new User(); user.setAge(20); set.add(user); System.out.println(set.contains(user)); user.setAge(21); System.out.println(set.contains(user)); } } true true Process finished with exit code 0

 

案例二

重写了 hashCode 和equals()

public class User { private String userName; private Integer age; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @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(userName, user.userName) && Objects.equals(age, user.age); } @Override public int hashCode() { return Objects.hash(userName, age); } } public class Main { public static void main(String[] args) { HashSet<User> set = new HashSet<>(); User user = new User(); user.setAge(20); set.add(user); System.out.println(set.contains(user)); user.setAge(21); System.out.println(set.contains(user)); } } true false Process finished with exit code 0

 

最新回复(0)