我正在尝试为比较它们的字段并在它们相等时返回 true 的对象编写一个 equals 方法。
private int x, y, direction;
private Color color;
public boolean equals(Ghost other){
if (this.x == other.x && this.y == other.y &&
this.direction == other.direction && this.color == other.color)
return true;
else
return false;
}
这有什么问题吗?
最佳答案
自 color
appears to be一个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);
}
关于java - 对象的等于方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3950439/