Java How to override equals and hashCode
By:Roy.LiuLast updated:2019-08-17
Some Java examples to show you how to override equals and hashCode.
1. POJO
To compare two Java objects, we need to override both equals and hashCode (Good practice).
User.java
public class User { private String name; private int age; private String passport; //getters and setters, constructor
User user1 = new User("mkyong", 35, "111222333"); User user2 = new User("mkyong", 35, "111222333"); System.out.println(user1.equals(user2)); // false
2. Classic Way
The 17 and 31 hash code idea is from the classic Java book – effective Java : item 9
User.java
public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; User user = (User) o; return user.name.equals(name) && user.age == age && user.passport.equals(passport); //Idea from effective Java : Item 9 @Override public int hashCode() { int result = 17; result = 31 * result + name.hashCode(); result = 31 * result + age; result = 31 * result + passport.hashCode(); return result;
2. JDK 7
For JDK 7 and above, you can use the new Objects class to generate the equals and hash code values.
User.java
import java.util.Objects; public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; User user = (User) o; return age == user.age && Objects.equals(name, user.name) && Objects.equals(passport, user.passport); @Override public int hashCode() { return Objects.hash(name, age, passport);
3. Apache Commons Lang
Alternatively, you can use the Apache Commons Lang EqualsBuilder and HashCodeBuilder function.
User.java
import org.apache.commons.lang3.builder; public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; User user = (User) o; return new EqualsBuilder() .append(age, user.age) .append(name, user.name) .append(passport, user.passport) .isEquals(); @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(name) .append(age) .append(passport) .toHashCode();
4. Test again
After overrides both equals and hashCode.
User user1 = new User("mkyong", 35, "111222333"); User user2 = new User("mkyong", 35, "111222333"); System.out.println(user1.equals(user2)); // true
References
- Wikipedia : Java hashCode()
- The 3 things you should know about hashCode()
- JDK 7 Objects JavaDoc
- Apache Commons Lang
- HashCodeBuilder JavaDoc
- Stackoverflow : Overriding equals and hashCode in Java?
From:一号门
Previous:Windows 10 Edit Hosts file
COMMENTS