@EqualsAndHashCode注解的小坑,你踩中了吗?

Lombok中使用@EqualsAndHashCode注解

  1. 此注解会生成 equals(Object other)hashCode() 方法。
  2. 它默认使用非静态,非瞬态的属性
  3. 可通过参数 exclude 排除一些属性
  4. 可通过参数 of 指定仅使用哪些属性
  5. 它默认仅使用该类中定义的属性且不调用父类的方法,可以通过 classSuper = true 解决,让其生成的方法中调用父类的方法。

当有多个类有相同的部分属性,把它们定义到父类,恰好id也在父类中,那么当这些对象进行比较时,因为Lombok生成的 equals(Object other)hashCode() 方法而判定为相等。

@Data
public class People {
    private Integer id;
}

@Data
public class User extends People {
    private String name;
    private Integer age;
}

public static void main(String[] args) {
    User user1 = new User();
    user1.setName("jiangxp");
    user1.setAge(18);
    user1.setId(1);

    User user2 = new User();
    user2.setName("jiangxp");
    user2.setAge(18);
    user2.setId(2);

    System.out.println(user1.equals(user2));
}

输出结果:true

但实际上,两条数据是不相等的,因为Id完全不一样的。

如果将 @EqualsAndHashCode 改成 @EqualsAndHashCode(callSuper = true) 就可以得到正确的结果。反编译修改后的class

public boolean equals(Object o) {
    if (o == this) {
        return true;
    } else if (!(o instanceof User)) {
        return false;
    } else {
        User other = (User)o;
        if (!other.canEqual(this)) {
            return false;
        } else if (!super.equals(o)) {    // 注意
            return false;
        } else {
            Object this$name = this.getName();
            Object other$name = other.getName();
            if (this$name == null) {
                if (other$name != null) {
                    return false;
                }
            } else if (!this$name.equals(other$name)) {
                return false;
            }

            Object this$age = this.getAge();
            Object other$age = other.getAge();
            if (this$age == null) {
                if (other$age != null) {
                    return false;
                }
            } else if (!this$age.equals(other$age)) {
                return false;
            }

            return true;
        }
    }
}

 public int hashCode() {
    int PRIME = true;
    int result = super.hashCode(); //注意
    Object $name = this.getName();
    result = result * 59 + ($name == null ? 43 : $name.hashCode());
    Object $age = this.getAge();
    result = result * 59 + ($age == null ? 43 : $age.hashCode());
    return result;
}

参考引用:

Lombok EqualsAndHashCode 的用法

lombok @EqualsAndHashCode 注解的影响

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值