Home >Java >javaTutorial >How Do I Correctly Override the `equals` Method for Object Comparison in Java?
Understanding Object Equality in Java
To compare the equality of two objects in Java, one often employs the equals method. In the scenario described, the aim is to override the equals method for a People class with name and age fields, to facilitate comparisons between People objects.
The initial implementation presented used the equals method for the age field, which is of type Integer. However, as pointed out, the equals method is specifically designed to compare String objects.
Solution: Comparing Integer Fields
To compare Integer fields, it is recommended to use the == operator instead of the equals method. The == operator compares the values of the primitive data types directly, rather than invoking the equals method.
Implementing Equals Correctly
The correct implementation of the equals method for the People class should be as follows:
@Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != this.getClass()) { return false; } final People other = (People) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if (this.age != other.age) { return false; } return true; }
In this implementation:
The above is the detailed content of How Do I Correctly Override the `equals` Method for Object Comparison in Java?. For more information, please follow other related articles on the PHP Chinese website!