I looked at one of your previous questions, and it seems the color
field is a Color
. I'm going to assume that you haven't changed the type of that field.
That's a class, and therefore a reference type, which means you need to use equals()
or a similar method to compare the colors (I haven't used that class before, so I can't tell you exactly which method to use).
if (/* ... && */ this.color.equals(other.color)) {
As in the comments, using ==
to compare reference types is really comparing memory addresses in Java. It'll only return true
if they both refer to the same object in memory.
EDIT: akf points out that you need to use the base Object
class for your parameter, otherwise you're not overriding Object.equals()
, but actually overloading it, i.e. providing a different way of calling the same-named method. If you happen to pass an object of a totally different class by accident, unexpected behavior might occur (although then again if they are of different classes it will return false
correctly anyway).
@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);
}