It is well-known that the equals()
method of an object, if not overridden, is a "shallow comparison" that is equivalent to using the "==" operator. (See, for example, https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html.)
Question: why doesn't Java provide a "deep-comparison" equals()
method by default? That is, one that will invoke equals()
on each of its instance variables recursively. Eventually, the recursion will reach primitive types and stop. Are there any downsides if this deep-comparison equals was the default?
Are there any downsides if this deep-comparison equals was the default?
Yes. These include:
The current default implementation is fast and makes no assumptions. It's a good default. Sometimes you will need to override the default, using your knowledge about what the logical value of the object contains, regardless of its root physical representation.
A deep compare is much more complex and time consuming than a comparison of two references. This might be ok for simple objects, but when you have really complex data structures (e.g. a tree with ten thousand elements) how should the system know how "deep" the compare should be?
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