user3453226
user3453226

Reputation:

Should I override the Object.equals(Object) method?

I have two instances of the same class.

public class Gilda {
    private String nome;
    public Gilda(String nome) {
        this.nome = nome;
    }
    // More stuff
}

When trying to compare them via Object.equals(Object) method, it returns false. This is strange because nome has the same value on both of these instances.

How does the comparison work? Is this the expected behavior? Should I override that method?

Upvotes: 0

Views: 97

Answers (2)

Ofer Lando
Ofer Lando

Reputation: 824

You must override the equals method - and accordingly - you must override hashCode with it.

Upvotes: 0

Todd
Todd

Reputation: 31700

Yes, you have to override it. By not doing that, you are using the version that Object itself provides, which defaults to reference equality (they are the same "physical" object).

Depending on your IDE, this could be written automatically for you. For instance, IntelliJ 14 just wrote this for me:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Gilda gilda = (Gilda) o;
    if (nome != null ? !nome.equals(gilda.nome) : gilda.nome != null) return false;

    return true;
}        

And of course, don't forget hashCode, which should always be done at the same time as equals:

@Override
public int hashCode() {
    return nome != null ? nome.hashCode() : 0;
}

Upvotes: 5

Related Questions