Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The general usage contract for equals() has been put forth verbatim from the . The Java specification says:

  • It is reflexive: For any reference value x, x.equals(x) must return true.
  • It is symmetric: For any reference values x and y, x.equals(y) must return true if and only if y.equals(x) returns true.
  • It is transitive: For any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) must return true.
  • It is consistent: For any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified.
  • For any non-null reference value x, x.equals(null) must return false.

Wiki Markup
Do not violate any of these five conditions while overriding the {{equals}} method. Mistakes due resulting from a violation of to the first postulate are quite infrequent; it is thusconsequently omitted from this discussion. The second and third conditions are highlighted. The rule for consistency implies that mutable objects may not satisfy the {{equals}} contract. It is good practice to avoid defining {{equals()}} implementations sothat as to use unreliable data sources such as IP addresses \[[Bloch 08|AA. Java References#Bloch 08]\] and caches. The final condition about the comparison with {{null}} is typically violated when the {{equals()}} code throws an exception instead of returning {{false}}. SinceBecause this does not constitute a security vulnerability, it is beyond the scope of this discussion.  

...

Noncompliant Code Example

This noncompliant code example violates transitivity though although it follows the symmetry condition. This is because the first two statements print true while the third prints false. A practical implementation issue is intermingling of java.sql.Timestamp and java.util.Date classes. There is a disclaimer about the erratic behavior in the documentation for the Timestamp class.

...

Wiki Markup
"There are some classes in the Java platform libraries that do extend an instantiable class and add a value component. For example, {{java.sql.Timestamp}} extends {{java.util.Date}} and adds a nanoseconds field. The equals implementation for {{Timestamp}} does violate symmetry and can cause erratic behavior if {{Timestamp}} and {{Date}} objects are used in the same collection or are otherwise intermixed." \[[Bloch 08|AA. Java References#Bloch 08]\]

...