这并不是那么容易,这比你想象的更多的陷阱。
您的equals方法必须允许拥有属于您正在编写它的类以外的类的对象。你所要做的就是检查是否该参数是也是一对:
if (otherObject == null) return false;
if (otherObject.getClass() != Pair.class) return false;
后该检查通过,你可以安全地转换,并指定投对象到一个新的局部变量:
Pair otherPair = (Pair)otherObject;
然后使用otherPair上的字段进行等号检查。此时,您已完成otherObject参数,其余的equals方法不应再引用它。
整个事情看起来像
public boolean equals(Object otherObject) {
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Pair otherPair = (Pair)otherObject;
return otherPair.fst.equals(this.fst) && otherPair.snd.equals(this.snd);
}
假设FST和SND不允许为空。在空成员上调用equals方法将导致NullPointerException。为了避免NPE如果FST或SND为空,检查成员对他们的呼吁平等之前是空的:
public boolean equals(Object otherObject) {
// check if references are the same
if (this == otherObject) return true;
// check if arg is null or something other than a Pair
if (otherObject == null) return false;
if (getClass != otherObject.getClass()) return false;
Pair otherPair = (Pair)otherObject;
// check if one object's fst is null and the other is nonnull
if (otherPair.fst == null || this.fst == null) {
if (otherPair.fst != null || this.fst != null) return false;
}
// check if one object's snd is null and the other is nonnull
if (otherPair.snd == null || this.snd == null) {
if (otherPair.snd != null || this.snd != null) return false;
}
// each member is either null for both or nonnull for both
return ((otherPair.fst == null && this.fst == null) || otherPair.fst.equals(this.fst))
&& ((otherPair.snd == null && this.snd == null) || otherPair.snd.equals(this.snd));
}
这最后一位是讨厌写,集成开发环境会产生这个东西给你。以下是Eclipse生成的内容:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pair other = (Pair) obj;
if (fst == null) {
if (other.fst != null)
return false;
} else if (!fst.equals(other.fst))
return false;
if (snd == null) {
if (other.snd != null)
return false;
} else if (!snd.equals(other.snd))
return false;
return true;
}
还记得实施hashCode。
你为什么使用'otherObject'而不是'aPair'? –