java equals, hashCode overriding 작성법

simuruk wiki
 1 public class SumClass implements Serializable {
 2     private Date someDate;
 3     private String a;
 4     private String b;
 5     private String c;
 6 
 7     @Override
 8     public boolean equals(Object obj) {
 9 
10         if (obj == null) {
11             return false;
12         }
13 
14         if (obj == this) {
15             return true;
16         }
17 
18         if (!(obj instanceof SumClass)) {
19             return false;
20         }
21 
22         SumClass sdk = (SumClass) obj;
23         return someDate.equals(sdk.someDate) && a.equals(sdk.a) && b.equals(sdk.b) && c.equals(sdk.c);
24 
25     }
26 
27     @Override
28     public int hashCode() {
29         int result = someDate != null ? someDate.hashCode() : 0;
30         result = 31 * result + ( a != null ? a.hashCode() : 0 );
31         result = 31 * result + ( b != null ? b.hashCode() : 0 );
32         result = 31 * result + ( c != null ? c.hashCode() : 0 );
33         return result;
34     }
35 
36 }
  • 간단히 아래처럼 lombok을 사용할수 있다.
  • @EqualsAndHashCode(of = {"someDate", "a", "b", "c"}, callSuper = false)
  • 31로 제곱 하는 이유