Skip to content

Instantly share code, notes, and snippets.

@rafali
Last active December 14, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafali/5161739 to your computer and use it in GitHub Desktop.
Save rafali/5161739 to your computer and use it in GitHub Desktop.
Correct equals and hashCode
//from http://developer.android.com/reference/java/lang/Object.html
// 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));
}
@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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment