How To Write an Equality Method in Java
artima.com
artima.com
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.
Or, y'know, just don't use mutable data for keys. I thought that was what people were supposed to do anyway.
On the other hand, C++ containers have all sorts of other problems (iterator invalidation to name one)...
C# has the value type concept, but I don't think it's enforced on container keys.
Sorry to be so negative.
Shouldn't there be some sort of in-language capacity to address this? A "Warning: equals and hashCode not codefined" seems like it would help.
You could add two keywords like /notice/ and /keep/. If a parent class's function definition of foo has /notice bar/, overrides of foo could allow the new class to inherit bar with /keep bar/, or warn if neither a keep statement or an override are present.