官方文档:https://projectlombok.org/features/EqualsAndHashCode
网友文章参考:http://www.pianshen.com/article/1619125852/
不加 @EqualsAndHashCode 时:
public class Apple { private String color; public Apple(String color) { this.color = color; } public static void main(String[] args) { Apple a1 = new Apple("green"); Apple a2 = new Apple("red"); // hashMap stores apple type and its quantity HashMap<Apple, Integer> m = new HashMap<Apple, Integer>(); m.put(a1, 10); m.put(a2, 20); System.out.println(m.get(new Apple("green"))); //输出为 null System.out.println(m.get(a1)); //输出为 10 } }
加 @EqualsAndHashCode 时:
@EqualsAndHashCode public class Apple { private String color; public Apple(String color) { this.color = color; } public static void main(String[] args) { Apple a1 = new Apple("green"); Apple a2 = new Apple("red"); // hashMap stores apple type and its quantity HashMap<Apple, Integer> m = new HashMap<Apple, Integer>(); m.put(a1, 10); m.put(a2, 20); System.out.println(m.get(new Apple("green"))); //输出为 10 System.out.println(m.get(a1)); //输出为 10 } }