Question

I want to override the equals method. But in my class are two integers. I want to ask you if the equalsMethode is correct.

like this?

thank you

edit 1: my problem is, i want to remove an object of typ field of a

Était-ce utile?

La solution

Other than a couple of syntax errors, the implementation is not incorrect. However, the conversions to string are unnecessary:

return other.getRow() == getRow() && other.getColumn() == getColumn();

Other points:

  1. The if (this == obj) check is redundant.

  2. The if (getClass() != obj.getClass()) check may or may not be desirable, depending on whether you intend to ever subclass Field (I note that it is not declared final).

Last but not least, having overridden equals(), you should also override hashCode(). See What issues should be considered when overriding equals and hashCode in Java? for a discussion.

Autres conseils

This is your equals method:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Field other = (Field) obj;
    if (column != other.column)
        return false;
    if (row != other.row)
        return false;
    return true;
}

and this is your hashCode mthod:

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + column;
        result = prime * result + row;
        return result;
    }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top