Kovács Imre
Kovács Imre

Reputation: 715

Canonical equals() method for Java as on Android Developers site

Here's how the site suggests you to write an equals() method.

   @Override 
   public boolean equals(Object o) {
     if (this == o) {
       return true;
     }

     if (!(o instanceof MyType)) {
       return false;
     }

     MyType lhs = (MyType) o;

     return primitiveField == lhs.primitiveField &&
             referenceField.equals(lhs.referenceField) &&
             (nullableField == null ? lhs.nullableField == null
                                    : nullableField.equals(lhs.nullableField));
   }

Now, I am surely misunderstanding something, but suppose you have two MyType objects m1 and m2, and e.g. if m1.referenceField is null, this is not going to work, because when it reaches

referenceField.equals(lhs.referenceField)

it will throw a NullPointerException. Where could be my logic error?

Upvotes: 1

Views: 170

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500635

I believe the point is that this would be a type where referenceField was guaranteed to be non-null, e.g. it's checked in the constructor.

Compare this with nullableField, where the nullity is checked as part of equals.

Upvotes: 1

Related Questions