Java – Implementing Equals Method for Objects

equalsjavaobject

I'm trying to write an equals method for objects that compares their fields and return true if they're equal.

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;
}

What could be wrong with this?

Best Answer

Since color appears to be a Color, that's a class, and therefore a reference type, which means you need to use equals() to compare the colors.

if (/* ... && */ this.color.equals(other.color)) {

As noted 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.


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);
}
Related Question