Home >Java >javaTutorial >How Do I Correctly Override the `equals` Method for Object Comparison in Java?

How Do I Correctly Override the `equals` Method for Object Comparison in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-12-22 18:32:09846browse

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:

  • It first checks if the passed object is null, different class, or has a null name field.
  • If those checks pass, it uses the == operator to compare the age fields.
  • It returns true if all the comparisons evaluate to true, otherwise false.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn