Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Object.equals() what was the intention? [closed]

Tags:

java

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.

like image 948
rgeorge Avatar asked May 27 '13 14:05

rgeorge


2 Answers

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).

like image 70
Jeff Storey Avatar answered Sep 29 '22 14:09

Jeff Storey


It was a pretty good language design decision to include equals in Java.

  • Decades of experience have shown that different classes of object have different equality semantics. You need a mechanism to express this, and prividing a polymorphic equals method is a decent approach.
  • Object identity (== 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)
  • If you don't define 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.
  • If you don't provide 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.

like image 22
mikera Avatar answered Sep 29 '22 16:09

mikera