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:
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...
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.
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.
We can override the equals method in our class to check whether two objects have same data or not.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With