Skip to content

Instantly share code, notes, and snippets.

@hackjutsu
Last active January 23, 2017 06:46
Show Gist options
  • Save hackjutsu/8c26b71a29b18467d1e05bb9b1efeff7 to your computer and use it in GitHub Desktop.
Save hackjutsu/8c26b71a29b18467d1e05bb9b1efeff7 to your computer and use it in GitHub Desktop.
[Snippet for correct implementation of equals() and hashcode()] http://www.javaranch.com/journal/2002/10/equalhash.html
public class Test {
private int num;
private String data;
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if ((obj == null) || (obj.getClass() != this.getClass())) {
return false;
}
// object must be Test at this point
Test test = (Test) obj;
return num == test.num &&
(data == test.data || (data != null && data.equals(test.data)));
}
public int hashCode() {
int hash = 7;
hash = 31 * hash + num;
hash = 31 * hash + (null == data ? 0 : data.hashCode());
return hash;
}
// other methods
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment