我想实现一个自定义equals()
方法,我有一个类,Board
。该方法比较每个板的阵列,定义为private int[] board
,如果数组相等则返回true,否则返回false。我知道有一些“陷阱”,在测试平等,所以我在想,如果下面的代码是最佳的和足够的真正测试平等:测试平等的足够方法
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);
}
您在开始时忘记了空检查。如果y为null,则会中断 – cowls 2013-03-05 17:19:03