我想實現一個自定義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