Last active
January 23, 2017 06:46
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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