01 import lombok.EqualsAndHashCode;
02
03 @EqualsAndHashCode(exclude={"id", "shape"})
04 public class EqualsAndHashCodeExample {
05 private transient int transientVar = 10;
06 private String name;
07 private double score;
08 private Shape shape = new Square(5, 10);
09 private String[] tags;
10 private int id;
11
12 public String getName() {
13 return this.name;
14 }
15
16 @EqualsAndHashCode(callSuper=true)
17 public static class Square extends Shape {
18 private final int width, height;
19
20 public Square(int width, int height) {
21 this.width = width;
22 this.height = height;
23 }
24 }
25 }
|
01 import java.util.Arrays;
02
03 public class EqualsAndHashCodeExample {
04 private transient int transientVar = 10;
05 private String name;
06 private double score;
07 private Shape shape = new Square(5, 10);
08 private String[] tags;
09 private int id;
10
11 public String getName() {
12 return this.name;
13 }
14
15 @Override public boolean equals(Object o) {
16 if (o == this) return true;
17 if (o == null) return false;
18 if (!(o instanceof EqualsAndHashCodeExample)) return false;
19 EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o;
20 if (!other.canEqual(this)) return false;
21 if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
22 if (Double.compare(this.score, other.score) != 0) return false;
23 if (!Arrays.deepEquals(this.tags, other.tags)) return false;
24 return true;
25 }
26
27 @Override public int hashCode() {
28 final int PRIME = 31;
29 int result = 1;
30 final long temp1 = Double.doubleToLongBits(this.score);
31 result = (result*PRIME) + (this.name == null ? 0 : this.name.hashCode());
32 result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
33 result = (result*PRIME) + Arrays.deepHashCode(this.tags);
34 return result;
35 }
36
37 public boolean canEqual(Object other) {
38 return other instanceof EqualsAndHashCodeExample;
39 }
40
41 public static class Square extends Shape {
42 private final int width, height;
43
44 public Square(int width, int height) {
45 this.width = width;
46 this.height = height;
47 }
48
49 @Override public boolean equals(Object o) {
50 if (o == this) return true;
51 if (o == null) return false;
52 if (!(o instanceof Square)) return false;
53 Square other = (Square) o;
54 if (!other.canEqual(this)) return false;
55 if (!super.equals(o)) return false;
56 if (this.width != other.width) return false;
57 if (this.height != other.height) return false;
58 return true;
59 }
60
61 @Override public int hashCode() {
62 final int PRIME = 31;
63 int result = 1;
64 result = (result*PRIME) + super.hashCode();
65 result = (result*PRIME) + this.width;
66 result = (result*PRIME) + this.height;
67 return result;
68 }
69
70 public boolean canEqual(Object other) {
71 return other instanceof Square;
72 }
73 }
74 }
|