Java 重写的equals和hashCode在自定义对象上不起作用;
我有一个下面的物体Java 重写的equals和hashCode在自定义对象上不起作用;,java,spring,junit,Java,Spring,Junit,我有一个下面的物体 class CustomObj{ private String name; private String dept; public String getName(){ return this.name; } public String getDept(){ return this.dept; } private CustomObj(){ } private CustomObj(CustomO
class CustomObj{
private String name;
private String dept;
public String getName(){
return this.name;
}
public String getDept(){
return this.dept;
}
private CustomObj(){
}
private CustomObj(CustomObjBuilder builder){
this.name = builder.name;
this.dept= builder.dept;
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomObj that = (CustomObj) o;
return that.name.equals(name) &&
that.dept.equals(dept);
}
@Override
public int hashCode() {
int result = 31;
result = 31 * result + name.hashCode();
result = 31 * result + dept.hashCode();
return result;
}
public static class CustomObjBuilder{
private String name;
private String dept;
public CustomObjBuilder(String name, String dept){
this.name = name;
this.dept = dept;
}
public CustomObjBuilder setName(String name){
this.name = name;
return this;
}
public CustomObjBuilder setDept(String dept){
this.dept = dept;
return this;
}
public CustomObj build(){
return new CustomObj(this);
}
}
}
以及使用上面的
class XYZ{
Set<CustomObj> obj = new HashSet<CustomObj>();
public void process(String a, String b){
CustomObj o = new CustomObj.CustomObjBuilder(a,b).build();
if(!obj.contains(o)){
obj.add(o);
}
}
}
因为我重写了hascode和equals,所以上面两个都是相等的,当第二次调用进程时,控件不应该进入if!obj.containso第二次和集合大小应为1。但是当我运行测试obj.addo时;它叫了两次。但是equals方法中的这个对象和那个对象的值是相同的,但是
that.name.equals(name) && that.dept.equals(dept)
在CustomObj内部返回false。有人能帮我理解为什么吗?代码很好。要验证添加sysout以检查集合大小,请执行以下操作:
您的代码运行良好。如果obj.containso第二次失败。代码运行正常。是什么让你认为控制装置进入了内部?
that.name.equals(name) && that.dept.equals(dept)
class XYZ {
Set<CustomObj> obj = new HashSet<CustomObj>();
public void process(String a, String b) {
CustomObj o = new CustomObj.CustomObjBuilder(a, b).build();
if (!obj.contains(o)) { // Fails second time for your use case.
obj.add(o);
}
System.out.println(obj.size()); // This is 1 in your use case.
}
}