Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can .equals be overridden such that a.equals(a) returns false?

Tags:

java

equals

I'm still pretty fresh to all this, but I'm working on attaining my OCAJP certification (Java). I remembered reading previously that the .equals method could be overridden when I came to this question:

Question from Enthuware prep materials:

Now these questions have been pretty evil as far as I'm concerned. Twisting every little thing you think you know to force you to learn all the minutiae. Now I had guessed E, but I didn't think D was correct. I mean 99.9% of the time, of course, but I thought it was a trick question based on the wording.

This got me thinking, is that true? I mean, if I get the question on the exam, I know how to answer it now, but in the deep dark abyss of overriding madness, is it possible to create a situation where a.equals(a) returns false? I feel like this would make Aristotle angry...

like image 499
Steve the Maker Avatar asked Aug 24 '15 05:08

Steve the Maker


People also ask

Is it possible for equals () to return false?

By default, the equals() method returns false if the two objects aren't the same instance... This may seem obvious but sometimes the default behavior is not what you want... Now the equals() method will return true if two instances of Payment have the same currency and value.

Can the equals method be overridden?

You can override the equals method on a record, if you want a behavior other than the default. But if you do override equals , be sure to override hashCode for consistent logic, as you would for a conventional Java class.

What is the reason for overriding equals () method?

We can override the equals method in our class to check whether two objects have same data or not.

Is it necessary to override hashCode and equals method?

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object. hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and Hashtable.


1 Answers

Note that a. b and c are instances of primitive wrapper classes (such as Integer, Double, etc...). These classes are final and cannot be extended, so you can't override their equals implementation.

Therefore a.equals(a) will always return true, since those classes implement equals properly.

like image 122
Eran Avatar answered Sep 27 '22 20:09

Eran