Skip to content

Instantly share code, notes, and snippets.

@arturotena
Last active August 29, 2015 14:02
Show Gist options
  • Save arturotena/d62685a4bbe8b0e6cfeb to your computer and use it in GitHub Desktop.
Save arturotena/d62685a4bbe8b0e6cfeb to your computer and use it in GitHub Desktop.
How to overwrite equals() and hashcode()
@Override
public boolean equals(Object other) {
if (this == other) return true;
if (!(other instanceof MyClass)) return false;
final MyClass that = (MyClass) other;
return this.intField == that.intField &&
this.booleanField == that.booleanField &&
(this.stringField == null ? this.stringField == null : this.stringField.equals(that.stringField)) &&
(this.objectField == null ? this.objectField == null : this.objectField.equals(that.objectField));
}
@Override
public int hashCode() {
int result = 17;
result = 37 * result + intField;
result = 37 * result + (booleanField ? 1 : 0);
result = 37 * result + (this.stringField == null ? 0 : stringField.hashCode());
result = 37 * result + (this.objectField == null ? 0 : objectField.hashCode());
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment