user1427661
user1427661

Reputation: 11794

Sufficient Method for Testing Equality

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

Answers (2)

Boris the Spider
Boris the Spider

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:

  1. It returns false if y is null - this reduces the amount of code a bit
  2. It does your check that y 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

Mikhail Vladimirov
Mikhail Vladimirov

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

Related Questions