关于java实体重写equals与hashcode

最近List<实体>转HashSet去重,遇到了重写equals与hashcode的问题,记录一下:

这是Object类关于这两个方法的源码

    public native int hashCode();

    public boolean equals(Object obj) {
        return (this == obj);
    }

可以看出,Object类默认的equals比较规则就是比较两个对象的内存地址。所以在进行去重时需重写equals

public class EntAlterListEntity {

    private String altItem;
    private Date altDate;
    
	public String getAltItem() {
		return altItem;
	}
	public void setAltItem(String altItem) {
		this.altItem = altItem;
	}
	public Date getAltDate() {
		return altDate;
	}
	public void setAltDate(Date altDate) {
		this.altDate = altDate;
	}

   @Override
   public boolean equals(Object o) {
       if(this == o){
           return true;
       }
       if(o == null){
           return false;
       }
 
       if(getClass() != o.getClass()){
           return false;
       }
       EntAlterListEntity entAlter = (EntAlterListEntity) o;
       //altDate判断
       if(altDate == null){
           if(entAlter.altDate !=null){
               return false;
           }
       }else{
    	   if(altDate.compareTo(entAlter.altDate)!=0){
	           return false;
    	   }
       }
       //altItem判断
       if(!StringUtils.equals(altItem, entAlter.altItem)){
           return false;

       return true;
   }
}

而hashcode是本地方法,java的内存是安全的,因此无法根据散列码得到对象的内存地址,但实际上,hashcode是根据对象的内存地址经哈希算法得来的。ArrayList是根据equals来判断是否包含,而不管hashCode是否不相等。而HashSet处理流程则不一样,先判断两个对象的hashCode方法是否一样,如果不一样,立即认为两个对象equals不相等,并不调用equals方法,当hashCode相等时,再根据equals方法判断两个对象是否相等(散列数据的快速存取)。即 hashCode 方法的常规协定:

(1)当obj1.equals(obj2)为true时,obj1.hashCode() == obj2.hashCode()必须为true 
(2)当obj1.hashCode() == obj2.hashCode()为false时,obj1.equals(obj2)必须为false

那么,如何重写hashCode呢?

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + (altItem== null ? 0 : altItem.hashCode());
        result = 31 * result + (altDate== null ? 0 : altDate.hashCode());
        return result;
    }

生成一个 int 类型的变量 result,并且初始化一个值,比如17,然后对类中每一个重要字段,也就是影响对象的值的字段,也就是 equals 方法里有比较的字段,进行以下操作:a. 计算这个字段的值 filedHashValue = filed.hashCode(); b. 执行 result = 31 * result + filedHashValue;

为什么要使用31?,以下是String hashCode 方法的源码

 /**
     * Returns a hash code for this string. The hash code for a
     * {@code String} object is computed as
     * <blockquote><pre>
     * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
     * </pre></blockquote>
     * using {@code int} arithmetic, where {@code s[i]} is the
     * <i>i</i>th character of the string, {@code n} is the length of
     * the string, and {@code ^} indicates exponentiation.
     * (The hash value of the empty string is zero.)
     *
     * @return  a hash code value for this object.
     */
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;

            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }

减少乘积的冲突,并且可以被优化

* 左移 << : 左边的最高位丢弃,右边补全0(把 << 左边的数据*2的移动次幂)
* 右移 >> : 把>>左边的数据/2的移动次幂
* 无符号右移 >>> : 无论最高位是0还是1,左边补齐0

 所以 : 31 * i = (i << 5) - i(左边  31*2=62,右边   2*2^5-2=62) - 两边相等,JVM就可以高效的进行计算啦

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值