怎样正确改写Equals方法

    技术2022-05-11  50

    地球人都知道,equals方法需要满足自反,对称,传递,一致,非空特性,如果我们需要在代码中改写equals方法,怎么样才能保证这几个特性呢?

    (1)使用==操作符来检查实参是都指向当前对象的一个对象

    (2)使用instanceof操作符检查实参是都为正确类型

    (3)将实参转换成正确对象

    (4)根据业务需求判断当前对象与实参对象是否相等

    (5)最后,必须进行检查传递,一致和对称

    如果满足了以上5点,基本上可以算是成功改写equals方法,当然还必须同时改写hasCode方法

    下面是一个改写的例子供大家参考

     

    public   boolean  equals( Object obj )     {        ifthis==obj ) return true;                if!( obj instanceof Base ) )            return false;                Base target = (Base)obj;                ifthis.getId()!=null && this.getId().length()>0 )        {            return this.getId().equals( target.getId() );        }                if( target.getId()!=null && target.getId().length()>0 )        {            return false;        }                return EqualsBuilder.reflectionEquals(this, obj);    }

     

    改写后的hashCode方法(使用common-lang)

    原理:如果id属性不为空,则直接使用id的hashCode,如果为空,则使用这个对象的所有属性来生成散列值

     

      public   int  hashCode() {        if(this.getId()!=null&&this.getId().length()>0){            return this.getId().hashCode();        }        return HashCodeBuilder.reflectionHashCode(this);    }

    最新回复(0)