Reputation: 11794
I want to implement a custom equals()
method for a class I have, Board
. The method compares the arrays of each board, defined as private int[] board
, returning true if the arrays are equal and false if they are not. I know there are some "gotchas" in testing equality, so I was wondering if the following code was optimal and sufficient for truly testing the equality:
public boolean equals(Object y) {
if (this.getClass() != y.getClass()) return false; //must be same class -- duh
Board that = (Board) y; //y cast as Board
int[] thisBoardCopy = this.getBoard(); //copy of current board
int[] thatBoardCopy = that.getBoard(); //copy of y's board
return Arrays.equals(thisBoardCopy, thatBoardCopy);
}
Upvotes: 0
Views: 95
Reputation: 61198
The usual idiom for writing .equals
methods in java is this:
public boolean equals(Object y) {
if(y == this) return true;
if(!(y instanceof Board.class)) return false;
final Board that = (Board) y; //y cast as Board
return Arrays.equals(getBoard(), that.getBoard());
}
The first test just speeds things up if it's the same Board
, the second test has two functions:
false
if y
is null
- this reduces the amount of code a bity
is of the right class.EDIT
I'm not sure what you mean by "copy" in your comments, I assume you mean "reference". If you are copying those arrays before passing them into the equals
I would suggest that you don't as this method can be called many many (many) times if this object finds its way into a Map
or Set
.
Upvotes: 2
Reputation: 13900
You better do
if (!this.getClass().equals (y.getClass())) return false;
otherwise there will be NullPointerException in case y
is null
.
No. This still throws NPE. Should be:
if (y == null || !this.getClass().equals (y.getClass())) return false;
Upvotes: 0