我看着one of your previous questions,它似乎color
字段是Color
。我会假设你没有改变那个领域的类型。
这是一个类,因此是一个引用类型,这意味着您需要使用equals()
或类似的方法来比较颜色(我之前没有使用过这个类,所以我不能准确地告诉你哪种方法使用)。
if (/* ... && */ this.color.equals(other.color)) {
正如评论,使用==
比较引用类型确实比较Java中的内存地址。如果它们都指向内存中的同一对象,它将仅返回true
。
编辑:akf points out,你需要使用基Object
类的参数,否则你不重写Object.equals()
,但实际上超载,即提供调用同名方法的不同方式。如果偶然碰巧传递了完全不同类的对象,可能会发生意外的行为(不过,如果它们属于不同的类,它将会正确返回false
)。
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Ghost))
return false;
// Cast Object to Ghost so the comparison below will work
Ghost other = (Ghost) obj;
return this.x == other.x
&& this.y == other.y
&& this.direction == other.direction
&& this.color.equals(other.color);
}
@fprime:你只需要一个return语句,而不需要'if'。 ;-) – 2010-10-16 19:33:29
打印出个人的结果,如果短语(例如'this.x == other。在if语句之前。看哪一个失败。 – 2010-10-16 19:34:58
被比较的任何变量对象类型,而不是原始类型? – 2010-10-16 19:35:03