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 aColor
, that's a class, and therefore a reference type, which means you need to useequals()
to compare the colors.As noted in the comments, using
==
to compare reference types is really comparing memory addresses in Java. It'll only returntrue
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 overridingObject.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 returnfalse
correctly anyway).