62,614
社区成员
发帖
与我相关
我的任务
分享
//EntityA
import org.apache.commons.lang.builder.HashCodeBuilder;
public class EntityA {
private String p1;
private String p2;
private String p3;
/*
省略Setter/Getter
*/
@Override
public int hashCode() {
//使用Commons的类生成Hashcode
return new HashCodeBuilder(17,37).append(p1).append(p2).toHashCode();
}
public int compareTo(EntityA o) {
return this.hashCode() - o.hashCode();
}
}
//EntityB
public class EntityB {
private String g1;
private String g2;
private String g3;
private String g4;
/*
省略Setter/Getter
*/
@Override
public int hashCode() {
//使用Commons的类生成Hashcode,当然,你也可以自己写,但是注意顺序!
return new HashCodeBuilder(17,37).append(p1).append(g4).toHashCode();
}
public int compareTo(EntityA o) {
return this.hashCode() - o.hashCode();
}
}
//实验代码
EntityA a = new EntityA();
EntityB b = new EntityB();
a.setP1("p1");
a.setP2("p2");
b.setG1("p1");
b.setG4("p2");
System.out.println(a.hashCode() == b.hashCode());
b.setG4("p3");
System.out.println(a.hashCode() == b.hashCode());
输出true
false
说明p1 = g1, p2 = g4的时候,这两个对象的hashcode是一样的。