DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Compact Equals Method

04.12.2005
| 2345 views |
  • submit to reddit
        
class Foo {
   private String string;
   private int i;
   [...]

   public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Foo)) return false;

        final Foo other = (Foo) o;

        if (string != null ? !string.equals(other.name) : other.name != null) return false;
        if (i != other.i) return false;
        [...]
        return true;
}
    

Comments

Snippets Manager replied on Wed, 2007/02/14 - 2:44pm

I'm afraid this one is wrong as well. :-) This runs into the classic problem with defining equals in the presence of subtyping. This code can only work reliably if you declare equals to be final (which is sometimes reasonable to do). If I extend Foo with Bar and add more fields to Bar, this code can result in foo.equals(bar) while !bar.equals(foo). An easy modification of the code to make it more robust is to replace the instanceof check with (o.getClass() == this.getClass()).