回答編集履歴

1

equalsメソッドの内容を変更

2018/03/12 13:30

投稿

umyu
umyu

スコア5846

test CHANGED
@@ -7,6 +7,40 @@
7
7
 
8
8
 
9
9
  0. ハッシュキーのインプレース変更をさけるためにhashCodeの計算に使用したフィールドは`final`で宣言してくださいな。
10
+
11
+
12
+
13
+ ---
14
+
15
+ 2018/03/12 追記
16
+
17
+
18
+
19
+ equalsメソッドのthis.employeeNameの判定はother.employeeNameを見るべきところを見ていないのでequalsメソッドに不具合があります。
20
+
21
+ ```Java
22
+
23
+ if (employeeName == null) {
24
+
25
+ if (this.employeeName != null) {
26
+
27
+ return false;
28
+
29
+ }
30
+
31
+
32
+
33
+ }
34
+
35
+ ```
36
+
37
+
38
+
39
+ equalsメソッドを[java.util.Objects#deepEquals](https://docs.oracle.com/javase/jp/8/docs/api/java/util/Objects.html#deepEquals-java.lang.Object-java.lang.Object-)を使った実装に変更しました。
40
+
41
+
42
+
43
+ ご参考まで。
10
44
 
11
45
 
12
46
 
@@ -46,51 +80,23 @@
46
80
 
47
81
  }
48
82
 
83
+ // 言語仕様にてinstanceof演算子は値が nullの時はfalseを返す。
84
+
49
- if (obj == null) {
85
+ if (!(obj instanceof Employee)) {
50
86
 
51
87
  return false;
52
88
 
53
89
  }
54
90
 
91
+ Employee other = (Employee) obj;
55
92
 
56
-
57
- if (getClass() != obj.getClass()) {
93
+ if (!Objects.deepEquals(this.employeeNo, other.employeeNo)) {
58
94
 
59
95
  return false;
60
96
 
61
97
  }
62
98
 
63
-
64
-
65
- Employee other = (Employee) obj;
66
-
67
- if (this.employeeNo != other.employeeNo) {
99
+ return Objects.deepEquals(this.employeeName, other.employeeName);
68
-
69
- return false;
70
-
71
- }
72
-
73
- if (employeeName == null) {
74
-
75
- if (this.employeeName != null) {
76
-
77
- return false;
78
-
79
- }
80
-
81
-
82
-
83
- } else if (!employeeName.equals(other.employeeName)) {
84
-
85
- return false;
86
-
87
- }
88
-
89
-
90
-
91
- return true;
92
-
93
-
94
100
 
95
101
  }
96
102
 
@@ -106,4 +112,6 @@
106
112
 
107
113
  }
108
114
 
115
+
116
+
109
117
  ```