The hashCode method must return the same value for two objects which are equal, and it should attempt to distribute the hashCode values relatively evenly. The first implementation, shown below, is efficient and correct, but it does not distribute the hashCode values at all. This hashCode implementation transforms any hash table into a list and forces linear searches. Clearly, this defeats the whole purpose of having an indexed data structure
public class MyPk
implements java.io.Serializable
{
public
String str;
public int i;
public byte b;
public MyPk() {}
private int hash = -1;
public int hashCode() {
if (hash == -1) {
hash = str.hashCode() ^ i ^ b;
}
return hash;
}
}
An efficient equals implementation
public final class MyPk ...
public boolean equals(Object o) {
if (o == this) return true;
if (o instanceof MyPk) {
MyPk other = (MyPk) o;
return other.hashCode() == hashCode() &&
other.i == i && other.b == b &&
other.str.equals(str);
} else {
return false;
}
}