See Also: Object Members
// Use @Override to avoid accidental overloading.
@Override public boolean equals(Object o) {
// Return true if the objects are identical.
// (This is just an optimization, not required for correctness.)
if (this == o) {
return true;
}
// Return false if the other object has the wrong type.
// This type may be an interface depending on the interface's specification.
if (!(o instanceof MyType)) {
return false;
}
// Cast to the appropriate type.
// This will succeed because of the instanceof, and lets us access private fields.
MyType lhs = (MyType) o;
// Check each field. Primitive fields, reference fields, and nullable reference
// fields are all treated differently.
return primitiveField == lhs.primitiveField &&
referenceField.equals(lhs.referenceField) &&
(nullableField == null ? lhs.nullableField == null
: nullableField.equals(lhs.nullableField));
}
If you override equals, you should also override hashCode: equal
instances must have equal hash codes.
See Effective Java item 8 for much more detail and clarification.
Follow this style to write a canonical hashCode method:
@Override public int hashCode() {
// Start with a non-zero constant.
int result = 17;
// Include a hash for each field.
result = 31 * result + (booleanField ? 1 : 0);
result = 31 * result + byteField;
result = 31 * result + charField;
result = 31 * result + shortField;
result = 31 * result + intField;
result = 31 * result + (int) (longField ^ (longField >>> 32));
result = 31 * result + Float.floatToIntBits(floatField);
long doubleFieldBits = Double.doubleToLongBits(doubleField);
result = 31 * result + (int) (doubleFieldBits ^ (doubleFieldBits >>> 32));
result = 31 * result + Arrays.hashCode(arrayField);
result = 31 * result + referenceField.hashCode();
result = 31 * result +
(nullableReferenceField == null ? 0
: nullableReferenceField.hashCode());
return result;
}
If you don't intend your type to be used as a hash key, don't simply rely on the default
hashCode implementation, because that silently and non-obviously breaks any future
code that does use your type as a hash key. You should throw instead:
@Override public int hashCode() {
throw new UnsupportedOperationException();
}
See Effective Java item 9 for much more detail and clarification.
For debugging convenience, it's common to override toString in this style:
@Override public String toString() {
return getClass().getName() + "[" +
"primitiveField=" + primitiveField + ", " +
"referenceField=" + referenceField + ", " +
"arrayField=" + Arrays.toString(arrayField) + "]";
}
The set of fields to include is generally the same as those that would be tested
in your equals implementation.
See Effective Java item 10 for much more detail and clarification.