How to Override the equals() Method in Java
Overriding the equals() method is essential for customizing the equality comparison behavior for custom objects in Java. Here's a comprehensive guide to help you do that effectively:
The Problem:
In the snippet given, you encountered an error when attempting to compare age fields using equals(), as it's designed for String objects. Integer values require the usage of == operator.
The Solution:
To resolve this error, use the == operator to compare primitive data types such as age. The modified code snippet is as follows:
public boolean equals(People other){ boolean result; if((other == null) || (getClass() != other.getClass())){ result = false; } // end if else{ People otherPeople = (People)other; result = name.equals(other.name) && age == other.age; } // end else return result; } // end equals
Additional Explanation:
1. Overriding Process:
2. Null Check:
3. Class Comparison:
4. Custom Comparison Logic:
Example:
The provided example overrides equals() for the Person class, comparing both name and age for equality:
public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != this.getClass()) { return false; } final Person other = (Person) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if (this.age != other.age) { return false; } return true; }
Conclusion:
Overriding the equals() method empowers you to define customized equality comparisons for your custom objects. By carefully following the steps and examples provided, you can effectively compare objects based on their specific attributes.
The above is the detailed content of How to Properly Override the equals() Method in Java?. For more information, please follow other related articles on the PHP Chinese website!