Pitfalls of Java Comparable interface

Java Comparable interface provides a way to do natural ordering for classes implementing the interface. Natural ordering makes sense for scalars and other quite simple objects, but when we come to more business oriented domain objects the natural ordering becomes much more complicated. A transaction object’s natural ordering from business manager’s point of view could be the value of the transaction, but from the system admin’s point of view the natural ordering could be the speed of the transaction. In most cases, there is no clear natural ordering for business domain objects.

Let’s assume that we have found a good natural ordering for a class like Company. We will use the company’s official name as the primary order field and the company id as the secondary. The Company class’ implementation could be as follows.

public class Company implements Comparable<Company> {     private final String id;    private final String officialName;     public Company(final String id, final String officialName) {        this.id = id;        this.officialName = officialName;    }     public String getId() {        return id;    }     public String getOfficialName() {        return officialName;    }     @Override    public int hashCode() {        HashCodeBuilder builder = new HashCodeBuilder(17, 29);        builder.append(this.getId());        builder.append(this.getOfficialName());        return builder.toHashCode();    }     @Override    public boolean equals(final Object obj) {        if (obj == this) {            return true;        }        if (!(obj instanceof Company)) {            return false;        }        Company other = (Company) obj;        EqualsBuilder builder = new EqualsBuilder();        builder.append(this.getId(), other.getId());        builder.append(this.getOfficialName(), other.getOfficialName());        return builder.isEquals();    }     @Override    public int compareTo(final Company obj) {        CompareToBuilder builder = new CompareToBuilder();        builder.append(this.getOfficialName(), obj.getOfficialName());        builder.append(this.getId(), obj.getId());        return builder.toComparison();    }}

Source : http://www.javacodegeeks.com/2013/08/pitfalls-of-java-comparable-interface.html

Back to Top