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