Home > Java > javaTutorial > What's the Difference Between `==` and `.equals()` When Comparing Objects in Java?

What's the Difference Between `==` and `.equals()` When Comparing Objects in Java?

Patricia Arquette
Release: 2024-12-26 11:19:09
Original
293 people have browsed it

What's the Difference Between `==` and `.equals()` When Comparing Objects in Java?

Comparing Objects with == Operator and .equals() Method

In object-oriented programming, comparing objects is crucial. This article explores the usage of two comparison methods: == operator and .equals().

== Operator

The == operator compares object references. It checks if two objects are the exact same instance, not just equivalent objects with the same contents. In the example code provided, object1 and object2 are distinct instances, so object1 == object2 returns false.

.equals() Method

In contrast, the .equals() method is used to compare object content. It typically checks if objects have the same properties or attributes. In the example code, .equals() checks if the a field of object1 equals the a field of object2. However, your custom equals() implementation is incorrect because it compares the objects themselves instead of comparing their a fields. This results in false being returned even though the a fields are identical.

Correct Implementation of .equals() Method

To correctly compare the a fields, you can use the following implementation:

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

This implementation checks if object2 is an instance of MyClass and then casts it appropriately. It then compares the a fields of the two objects.

Conclusion

The == operator compares object references, while the .equals() method compares object content. Proper use of both methods ensures accurate comparisons for your specific needs.

The above is the detailed content of What's the Difference Between `==` and `.equals()` When Comparing Objects in Java?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template