Sno*_*man 3 java equals object
我正在尝试为比较字段的对象编写一个equals方法,如果它们相等则返回true.
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;
}
Run Code Online (Sandbox Code Playgroud)
这可能有什么问题?
因为color 看起来是 a Color,这是一个类,因此是一个引用类型,这意味着你需要equals()用来比较颜色.
if (/* ... && */ this.color.equals(other.color)) {
Run Code Online (Sandbox Code Playgroud)
如注释中所述,==用于比较引用类型实际上是在比较Java中的内存地址.只有true当它们都引用内存中的同一个对象时才会返回.
akf指出你需要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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1400 次 |
| 最近记录: |