一个低效但正确的主键类 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; } } }
一个有效的equals实现 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; } }