Using CompareToBuilder to implement Comparable interface

Many a times, we need to implement the java.lang.Comparable interface. This interface has a single method int compareTo(Object o). Apache’s Commons Lang library provides a utility class – CompareToBuilder which makes it easy to write the compareTo() method. The method is consistent with with equals() and hashCode() methods built using EqualsBuilder and HashCodeBuilder (provided the same fields are used in all of them). A typical use of the class is as follows:

public class Account implements Comparable<Account> {
  private long id;
  private String firstName;
  private String lastName;
  private String emailAddress;
  private Date creationDate;

  public int compareTo(Account account) {
    return new CompareToBuilder()
        .append(this.id, account.id)
        .append(this.firstName, account.firstName)
        .append(this.lastName, account.lastName)
        .append(this.emailAddress, account.emailAddress)
        .append(this.creationDate, account.creationDate)
        .toComparison();
  }
}

We first create an instance of the CompareToBuilder. The append method takes two arguments – the two fields we want to compare. It returns an instance of CompareToBuilder so multiple calls to the append method can be chained (as in the above example). Finally we call the toComparison() method which returns the appropriate value to the caller.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s