-
-
Notifications
You must be signed in to change notification settings - Fork 679
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Issue #34 solution - hashcode for dominoes.
* Add a comment in the Domino class making explicit that changes in the Domino class are not accepted by the solution. (Believe me, I was really surprised during my first submission that my changes in the Domino class were rejected. As well as my mentee ). * Change the way equals and hashcode are implemented to use the min+max value of each side instead of left+right. * Added a constraint validation within the Domino class constructor, that tiles must have a maximum number of 9 on each side (this is needed for the hash implementation). * In the equals code, a comparison between a Domino and an Object would generate a class cast exception instead of the expected value, false.
- Loading branch information
Showing
2 changed files
with
32 additions
and
10 deletions.
There are no files selected for viewing
25 changes: 18 additions & 7 deletions
25
exercises/practice/dominoes/.meta/src/reference/java/Domino.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,30 +1,41 @@ | ||
import java.util.Objects; | ||
|
||
|
||
// This class can't be changed by the solution. | ||
// | ||
class Domino { | ||
private int left; | ||
private int right; | ||
private int hash; | ||
Domino(int left, int right) { | ||
if(left < 0 || left > 9 || right < 0 || right > 9 ) { | ||
throw new IllegalArgumentException("Domino tiles must have a number between 0 and 9 on each side"); | ||
|
||
} | ||
this.left = left; | ||
this.right = right; | ||
this.hash = Integer.min(left,right)+Integer.max(left,right)*10; | ||
} | ||
|
||
int getLeft() { | ||
return this.left; | ||
} | ||
|
||
int getRight() { | ||
return this.right; | ||
} | ||
|
||
@Override | ||
public boolean equals(Object o) { | ||
if (!o instanceof Domino ) { | ||
return false; | ||
} | ||
Domino otherDomino = (Domino) o; | ||
return (this.getLeft() == otherDomino.getLeft() && this.getRight() == otherDomino.getRight()) || | ||
(this.getLeft() == otherDomino.getRight() && this.getRight() == otherDomino.getLeft()); | ||
return this.hash == otherDomino.hash; | ||
} | ||
|
||
@Override | ||
public int hashCode() { | ||
return Objects.hash(left, right); | ||
return hash; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters