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; }
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!