Question

This is the code generated by Eclipse:

id is a String

@Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (id == null) {
            if (other.id != null)
                return false;
        } else if (!id.equals(other.id))
            return false;
        return true;
    }

What looks fishy to me are these line:

    if (id == null) {
        if (other.id != null)
            return false;
    } else if (!id.equals(other.id))
        return false;

Can someone explain to me what it does? I think what it does is check if id of this object is null and if id of the other object is null then the method returns true?

That seems a little strange to me?

Était-ce utile?

La solution

The whole part after the .getClass() test can be rewritten as:

return id == null ? other.id == null : id.equals(other.id);

That is to say, Eclipse's default .equals() will generate code so that if an instance field can be null, it considers equality (for this field at least) true if the other instance's field is also null; otherwise it compares the values.

(note that in the case where id is not null but other.id is, this will still work, since the .equals() contract stipulates that for any object o, o.equals(null) is false)

Now, it may, or may not, suit your needs; but what Eclipse does here seems logical to me.

Except that it generates code which is way too long ;)

Note that it requires that the id field obeys the .equals() contract!

Also, if you use Java 7, the code is even shorter:

return Objects.equals(id, other.id);

Autres conseils

As per eclipse, if there are 2 Person objects with id == null, then they are equal. You can remove it if it doesn't work in your context

You can replace it with below code, to avoid the same

if (id == null || other.id == null) {
       return false;
}

This method returns true if the id of the two objecs has the same value or the two are null.

if (id == null) {
        if (other.id != null)
            return false;

this code check if the id of this object is null and if the id of the other object is diferent of null return false

} else if (!id.equals(other.id))
     return false;

in the else as we know that id is diferent from null we can call the method equals of id and return false if the two id are not equal

If non of this conditions are meet, a true will be return.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top