4 ms·
> Here are four common pitfalls that can cause inconsistent behavior when overriding equals: 1. Defining equals with the wrong signature. 2. Changing equ
by russell 17y ago
> Here are four common pitfalls that can cause inconsistent behavior when overriding equals:
1. Defining equals with the wrong signature.
2. Changing equals without also changing hashCode.
3. Defining equals in terms of mutable fields.
4. Failing to define equals as an equivalence relation.
I have to call this a must read. Writing equals is straight forward, but there are are many ways to go wrong. In fact the article doesnt go far enough, because complex objects often have different levels of equality:
Is it the same object, by UID or some immutable field?
Is it equal by some subset of the contents?
Is it equal by some classification or hierarchy?
EDIT: by different kinds of equality, I mean such things as equalByContent for mutable fields or equalByLocation.
- brown9-2 17y agoBloch's Effective Java is the true must read here, 80% of this article simply re-iterates what was already published there (and in other places) already. The author just adds this "canEquals" idea, which sounds like it might become annoying and hard to maintain if you have more than a small handful of subclasses to deal with.