Equality Method for Objects

I am trying to write an equals method for objects that compares their fields and returns true if they are 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?

+3
source share
4 answers

So it color seems to color be a class and therefore a reference type, which means you need to use equals()colors to compare.

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

As noted in the comments, using ==reference types to compare really compares memory addresses in Java. It will only return trueif they both refer to the same object in memory.


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

, .

, ==. , , . , . , , java.lang.Strings, equals ( null).

+4

, this.color.equals(other.color).

, Color. (, Color.BLUE), . Color rgb, . , .equals() .

+3
source

Keep in mind that you are not overriding a method equalsfrom Object, since you are changing the type of parameter. Perhaps this method will not be used in all cases, as you might expect. Instead:

public boolean equals(Ghost other){

you must have:

public boolean equals(Object other){

and then internally check if the parameter is a otherparameter instanceof Ghostand apply as needed.

+3
source

Source: https://habr.com/ru/post/1769898/


All Articles