Przeglądaj źródła

Update GridPosition equals and implement hashCode

Tyler Matthews 9 lat temu
rodzic
commit
4494542f9a

+ 21
- 16
exercises/robot-simulator/src/example/java/GridPosition.java Wyświetl plik

@@ -9,21 +9,26 @@ final class GridPosition {
9 9
         this.y = y;
10 10
     }
11 11
 
12
-    /*
13
-     * This equals method is of deliberately narrow scope (only allows comparison with another GridPosition) to increase
14
-     * readability. In general, one should provide a full implementation of Object.equals(Object obj) and a
15
-     * corresponding implementation of Object.hashCode(). See
16
-     *
17
-     * https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)
18
-     *
19
-     * and
20
-     *
21
-     * https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()
22
-     *
23
-     * for more information.
24
-     */
25
-    boolean equals(final GridPosition gridPosition) {
26
-        return this.x == gridPosition.x && this.y == gridPosition.y;
27
-    }
12
+    @Override
13
+   public int hashCode() {
14
+      final int prime = 31;
15
+      int result = 1;
16
+      result = prime * result + x;
17
+      result = prime * result + y;
18
+      return result;
19
+   }
20
+
21
+   @Override
22
+   public boolean equals(Object obj) {
23
+      if (this == obj) {
24
+         return true;
25
+      } else if (obj == null || getClass() != obj.getClass()) {
26
+         return false;
27
+      } else if (x != ((GridPosition) obj).x || y != ((GridPosition)obj).y) {
28
+         return false;
29
+      } else {
30
+         return true;
31
+      }
32
+   }
28 33
 
29 34
 }