What do you think the primary motive for putting the equals method in java.lang.Object is? Most of the implementations that we override it with are domain-centric, i.e. in model classes. I'm yet to see an implementation of equals in a factory class or something equivalent.
My conclusion is that it was primarily put in to support the Java Collection API, so that it could deal with any Object. Else, it could have been left to be defined by specific domain designs.
PS: I know this thread may be more discussion oriented, but did not where else to get insight into this. I have tried to search far and wide for the answer to this, but always land up in discussions or explanations as to the difference between == and equals or the best practices of writing equals.
By putting equals in Object, it lets many other classes use the equals method without knowing specifically what type of object it will be dealing with. For example, HashMap and Hashtable use equals as part of their algorithms.
An alternative to putting it in Object would to have a separate interface that has the equals method (or possibly combine it with Comparable, the specifics are not important here though). But, I'm guessing the Java designers thought that having a default equals implementation would be useful in some situations (and this ensures that all objects have an equals method).
It was a pretty good language design decision to include equals in Java.
equals method is a decent approach.== in Java-land) is a reasonable default for equality testing but is not sufficient in many cases: often you want two objects to be considered equal even if they are not the same object (consider two lists with identical elements, for example)equals at the top of the object heirarchy (Object) so that it is implemented for every object, then it's hard / impossible to write generic code that deals with equality.equals as part of the core language, you can expect hundred of different and incompatible variations to spring up in the library ecosystem. Not pretty!My main criticism of the design of equals is that it assumes that you have a valid non-null object to call it on. Often true, but sometimes you need to check for nulls as well. As a result, I often end up using a static equalsWithNulls method or something simular that takes null checks into account before calling the regular equals.
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