覆盖的等于和hashCode在自定义对象上不起作用;

时间:2018-11-20 03:19:06

标签: 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(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);
       } 
   }
}

还有一个测试班

class TestXYX{

@Test
public void test(){
 XYZ xyz = new XYZ();
 xyz.process("TEST","TESTABC");
 xyz.process("TEST","TESTABC");
}
}

因为我重写了hascode和equals,以上两者均相等,并且第二次调用进程时,控件不应第二次进入if(!obj.contains(o)),并且集合的大小应为1。但是当我运行时测试obj.add(o);被调用两次。但是,此对象和equals方法内的objec的值都相同,但是

that.name.equals(name) && that.dept.equals(dept)
CustomObj内部的

返回false。有人可以帮我理解为什么吗?

1 个答案:

答案 0 :(得分:-1)

代码很好。要进行验证,请添加sysout来检查Set的大小:

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.
    }
}