teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

equalsメソッドの内容を変更

2018/03/12 13:30

投稿

umyu
umyu

スコア5846

answer CHANGED
@@ -4,7 +4,24 @@
4
4
 
5
5
  0. ハッシュキーのインプレース変更をさけるためにhashCodeの計算に使用したフィールドは`final`で宣言してくださいな。
6
6
 
7
+ ---
8
+ 2018/03/12 追記
9
+
10
+ equalsメソッドのthis.employeeNameの判定はother.employeeNameを見るべきところを見ていないのでequalsメソッドに不具合があります。
7
11
  ```Java
12
+ if (employeeName == null) {
13
+ if (this.employeeName != null) {
14
+ return false;
15
+ }
16
+
17
+ }
18
+ ```
19
+
20
+ 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-)を使った実装に変更しました。
21
+
22
+ ご参考まで。
23
+
24
+ ```Java
8
25
  import java.util.Objects;
9
26
 
10
27
  public class Employee {
@@ -22,29 +39,15 @@
22
39
  if (this == obj) {
23
40
  return true;
24
41
  }
42
+ // 言語仕様にてinstanceof演算子は値が nullの時はfalseを返す。
25
- if (obj == null) {
43
+ if (!(obj instanceof Employee)) {
26
44
  return false;
27
45
  }
28
-
29
- if (getClass() != obj.getClass()) {
30
- return false;
31
- }
32
-
33
46
  Employee other = (Employee) obj;
34
- if (this.employeeNo != other.employeeNo) {
47
+ if (!Objects.deepEquals(this.employeeNo, other.employeeNo)) {
35
48
  return false;
36
49
  }
37
- if (employeeName == null) {
38
- if (this.employeeName != null) {
39
- return false;
40
- }
41
-
42
- } else if (!employeeName.equals(other.employeeName)) {
50
+ return Objects.deepEquals(this.employeeName, other.employeeName);
43
- return false;
44
- }
45
-
46
- return true;
47
-
48
51
  }
49
52
 
50
53
  @Override
@@ -52,4 +55,5 @@
52
55
  return Objects.hash(employeeNo, employeeName);
53
56
  }
54
57
  }
58
+
55
59
  ```