Home > Java > javaTutorial > Why Does Comparing Custom Objects with `==` and `.equals()` Return `false` Even with Identical Field Values?

Why Does Comparing Custom Objects with `==` and `.equals()` Return `false` Even with Identical Field Values?

DDD
Release: 2024-12-25 03:11:09
Original
476 people have browsed it

Why Does Comparing Custom Objects with `==` and `.equals()` Return `false` Even with Identical Field Values?

Comparing Objects with .equals() and == Operator

Question:

In a custom class with a string field, why do object comparisons using both the == operator and .equals() method return false, even when the field values are identical?

Answer:

The == operator compares object references, determining if the objects being compared are the same object in memory. On the other hand, .equals() compares the contents of objects.

In this case, using == results in false because object1 and object2 are not the same object in memory, even though they have the same field value. To determine if the objects are equal in terms of field values, .equals() should be used.

Revised equals() Method:

The equals() method in the provided code can be revised to compare the values of the a field:

public boolean equals(Object object2) {
    if (object2 instanceof MyClass) {
        MyClass otherClass = (MyClass) object2;
        return this.a.equals(otherClass.a);
    }
    return false;
}
Copy after login

Additional Note:

When overriding equals(), it is generally recommended to also override hashCode() to maintain the contract that equal objects have equal hash codes.

The above is the detailed content of Why Does Comparing Custom Objects with `==` and `.equals()` Return `false` Even with Identical Field Values?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template