Google Objects.equal, useful but be careful.

Google have a nice equals method to make boiler plate equals easier to read. Particularly good if you have many attributes in the method. http://publicobject.com/2007/09/coding-in-small-with-google-collections_8175.html

Be careful to check that your objects are consistent with equals though.  I have mentioned this before.

In the following method I am using the Objects.equal with a BigDecimal class.  It does not work because BigDecimal equals treats 0 and 0.0 as not equal, which is probably not what you need.

public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }
    if (getClass() != obj.getClass()) {
      return false;
    }

    final TestEquals other = (TestEquals) obj;

    return Objects.equal(this.bigDecimal, other);
}

The common solution is to use the compareTo method instead like so.

  final TestEquals other = (TestEquals) obj;
  if (this.bigDecimal != other.bigDecimal &&
      (this.bigDecimal == null
      || this.bigDecimal.compareTo(other.bigDecimal) != 0)) {
    return false;
  }
  return true;

I will be using this technique, especially where the object has many attributes but I will be testing the equals method.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Comments are closed.