How to correctly use “equals” in Java?
In Java, the equals() method is used to compare whether two objects are equal. The key to correctly using the equals() method is to understand its implementation principle and usage scenarios.
- Rewrite the equals() method: By default, the equals() method compares the object’s reference rather than its content. Therefore, if you want to compare the content of objects, it is necessary to override the equals() method in the custom class and perform comparisons based on your own requirements.
For example, if there is a Person class and we need to compare the name and age attributes of two Person objects to see if they are equal, we can rewrite the equals() method as follows:
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Person person = (Person) obj;
return Objects.equals(name, person.name) && Objects.equals(age, person.age);
}
- Check for null and type: In the equals() method, it is necessary to first check if the passed object is null and if the types match. If the passed object is null, or the types do not match, return false immediately.
- When comparing object properties, it is recommended to use the Objects.equals() method instead of using “==” or equals() method, as Objects.equals() method automatically handles null values.
For example, the rewritten equals() method above uses the Objects.equals() method to compare the name and age properties.
- When overriding the equals() method, it is also necessary to override the hashCode() method in order to ensure the correctness when using hash-based data structures such as HashMap and HashSet.
In summary, the key to correctly using the equals() method is to compare objects based on their content, not just their references. When overriding the equals() method, it’s important to consider cases where the passed object is null or if the types match, and to compare object attributes using Objects.equals() method.