Why java `equals ()` does a deep comparison by default

It is well known that an equals()object's method , if not overridden, is a “shallow comparison" equivalent to using the "==" operator. (See, for example, https://docs.oracle.com/javase/tutorial/java/IandI/objectclass.html .)

Question: Why does Java not provide a equals()default “deep comparison” method ? That is, one that will recursively call equals()for each of its instance variables. In the end, recursion will reach primitive types and stop. Are there any flaws if this deep comparison value was the default?

+6
source share
3 answers

Are there any disadvantages if this deep comparison value was the default?

Yes. These include:

  • The default implementation cannot distinguish between links that are part of the logical value of an object and links that are simply associations with other objects. For example, let's say you have a Person class that refers to a company. You have two instances of Person with the same name, SSN, DOB, etc. One refers to an old company. You might want two instances of Person that refer to the same actual person to be equal, although it has an outdated association.
  • , , . . , , - .
  • . , . , . OutOfMemoryError.

. . , , , .

+10

, . , (, ), , "" ?

+3

For most objects, reference equality is the correct implementation. The "deep" are equal for the minority that supports the state. Not only would your suggestion run into the problems described here, it would be wrong for most types.

0
source

All Articles