SpringBoot - LOMBOK中@EqualsAndHashCode(callSuper = false)什么意思

SpringBoot - LOMBOK中@EqualsAndHashCode(callSuper = false)什么意思

import lombok.EqualsAndHashCode;
 
@EqualsAndHashCode(callSuper = false)
public class Person {
    private String name;
    private int age;
    
    // Constructor, getters and setters...
}
 
// Child class inherits from Person
public class Employee extends Person {
    private int id;
    
    // Constructor, getters and setters...
}
 
// Example usage
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
Employee employee = new Employee("Charlie", 35, 1001);
 
System.out.println(person1.equals(person2)); // prints false
System.out.println(person1.hashCode() == person2.hashCode()); // prints false
 
// Without @EqualsAndHashCode(callSuper = false), the following would print false
System.out.println(employee.equals(person1)); // prints false
System.out.println(employee.hashCode() == person1.hashCode()); // prints false
 
// With @EqualsAndHashCode(callSuper = false), the following prints true
System.out.println(employee.equals(new Employee("Charlie", 35, 1001))); // prints true
System.out.println(employee.hashCode() == new Employee("Charlie", 35, 1001).hashCode()); // prints true

Person类被标注为@EqualsAndHashCode(callSuper = false),因此它的equals()和hashCode()方法只比较name和age字段,而不比较任何从父类继承来的字段。Employee类继承自Person类,它也具有相同的行为。

@EqualsAndHashCode(callSuper = true) callSuper设置为true,表示使用子类中定义的属性以及父类的属性共同来生成 hashCode() 和 equals()方法,且在生成的 hashCode() 和 equals()方法中会调用父类的方法。

A. 如果比较两个对象时需要考虑超类中的成员属性,则使用 @EqualsAndHashCode(callSuper=true),才能得到正确的结果;

B. 如果仅使用当前子类中的字段,可以使用@EqualsAndHashCode(callSuper=false),或者不适用此注解,它这就是默认选项;

C. 如果类之间没有继承,仅当在一个类加上@Data时,不会有提示设置:@EqualsAndHashCode(callSuper=false)的警告,否则就会有警告提示。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zcy_code

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值