首先 @EqualsAndHashCode 标在子类上
1. callSuper = true,根据子类自身的字段值和从父类继承的字段值?来生成hashcode,当两个子类对象比较时,只有子类对象的本身的字段值和继承父类的字段值都相同,equals方法的返回值是true。
2.?callSuper = false,根据子类自身的字段值 来生成hashcode,?当两个子类对象比较时,只有子类对象的本身的字段值相同,父类字段值可以不同,equals方法的返回值是true。
package com.jt.test;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
/**
* @Author: ldj
* @Date: 2022/03/29/15:39
* @Description:
*/
public class HashCodeTest {
public static void main(String[] args) {
Cat cat1 = new Cat("黑色", "鲁鲁", 2);
Cat cat2 = new Cat("白色", "鲁鲁", 2);
System.out.println(cat1.equals(cat2)); //true callSuper = false
System.out.println(cat1.equals(cat2)); //false callSuper = true
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Animal {
private String color;
}
@Data
@EqualsAndHashCode(callSuper = false) //排除父类字段
class Cat extends Animal {
private String name;
private Integer age;
public Cat(String color, String name, Integer age) {
super(color);
this.name = name;
this.age = age;
}
}
|