Lombok 之 @EqualsAndHashCode 使用
一:作用
该注解的作用就是自动给 model bean 实现 equals 方法和 hashcode 方法。
二:参数
- @EqualsAndHashCode(callSuper = false ) 默认参数,父类属性不参与比较。
- @EqualsAndHashCode(callSuper = true) 调用父类属性,进行比较。
三:代码示例
(1)实体类
1 2 3 4 5 6 7
| @Data @AllArgsConstructor @NoArgsConstructor public class TV { private int id; private String name; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| @Data @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = true) public class XiaoMiTV extends TV { private float price; private String color;
public XiaoMiTV(int id, String name, float price, String color) { super(id, name); this.price = price; this.color = color; }
}
|
(2)测试类
1 2 3 4 5 6 7 8
| public class EqualsTest { public static void main(String[] args) { XiaoMiTV xiaoMiTV = new XiaoMiTV(1,"小米",99.99f,"red"); XiaoMiTV xiaoMiTV2 = new XiaoMiTV(2,"小米2",99.99f,"red"); System.out.println(xiaoMiTV.equals(xiaoMiTV2)); } }
|