[英]Sufficient Method for Testing Equality
我想为我所拥有的类实现一个自定义的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);
}
在java中编写.equals
方法的常用习惯是:
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());
}
第一个测试只是加速,如果它是同一个Board
,第二个测试有两个功能:
y
为null
,则返回false
- 这会减少代码量 y
是正确的类。 编辑
我不确定你的意见中的“复制”是什么意思,我认为你的意思是“参考”。 如果你在将它们传递给equals
之前复制这些数组,我建议你不要这样做,因为如果这个对象进入Map
或Set
,这个方法可以被调用很多次。
你最好做
if (!this.getClass().equals (y.getClass())) return false;
如果y
为null
,则会出现NullPointerException。
不,这仍然会引发NPE。 应该:
if (y == null || !this.getClass().equals (y.getClass())) return false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.