Listing 1:
An inefficient, but correct, primary key class
public class MyPk
implements java.io.Serializable
{
public String str;
public int i;
public byte b;
public MyPk() {}
public int hashCode() { return -1; }
public boolean equals(Object o) {
if ((o != null) && (MyPk.class.equals(o.getClass()))) {
MyPk other = (MyPk) o;
return other.str.equals(str) && other.i == i && other.b == b;
} else {
return false;
}
}
}
Listing 2:
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;
}
}