equals(), compareTo() and hashcode() compatible. If two objects are equal according to one, they should be equal in all three.

Not quite. You can, at least in theory, have two different objects return identical hash codes.[/NITPICK]

Adam Nace

Ranch Hand

Posts: 117

posted 11 years ago

Originally posted by Campbell Ritchie: [NITPICK] Not quite. You can, at least in theory, have two different objects return identical hash codes.[/NITPICK]

Indeed. Furthermore, the API for compareTo() specifies that compareTo() does not have to return equal simply because equals() does (and vice-versa).

It is strongly recommended, but not strictly required that (x.compareTo(y)==0) == (x.equals(y)). Generally speaking, any class that implements the Comparable interface and violates this condition should clearly indicate this fact. The recommended language is "Note: this class has a natural ordering that is inconsistent with equals."

- Adam [ July 31, 2006: Message edited by: Adam Nace ]

Stan James

(instanceof Sidekick)
Ranch Hand

Posts: 8791

posted 11 years ago

Good catch, guys. I once had written if equals() says true the others should agree. That much I think is actually true. Donno why I changed it. And I did say "should" rather than "MUST" on the other.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi