An object is characterized by its identity (location in memory) and state (actual data). While the ==
operator compares only the identities of two objects (to check if both the references refer to the same object), the equals
method defined in java.lang.Object
can compare the state as well, when customized by overriding. If a class defines an equals()
method, the provider has accounted for state comparison. If not, the default Object.equals()
implementation that is inherited from Object
compares only the references and may produce conterintuitive results. For example, the classes String
and StringBuffer
classes should be used with care should override the Object.equals()
method because they do not provide their own equals()
methodimplementation.
The equals()
method only applies to objects, not primitives. Also, immutable objects do not need to override it. There is no need to override equals
if checking logical equality is not useful. For example, Enumerated types have a fixed set of distinct values that may be compared using ==}}instead of {{equals()
. Note that Enumerated types do have an equals()
implementation that uses ==
internally and this default cannot be overridden. More generally, if a subclass inherits an implementation of equals
from a superclass and does not need additional functionality, overriding equals()
can be forgone.
...