Wednesday, September 22, 2004

Domain objects and compareTo

I wrote earlier about domain objects and boolean equals(Object) and how to handle primary keys. What about int compareTo(Object)? The same remarks about primary keys still apply, and the code pattern is:

public class Something implements Comparable {
    /* ... */

    public int compareTo(final Object o) {
        final Something that = (Something) o;
        int compareTo = firstPK.compareTo(that.firstPK);
        if (0 != compareTo) return compareTo;
        compareTo = secondPK.compareTo(that.secondPK);
        if (0 != compareTo) return compareTo;
        // ... likewise for other primary keys
        return lastPK.compareTo(that.lastPK);
    }
}

This sort of comparison method will group sorts by the order of comparison, so that firstPK groups together, then secondPK, etc.. If, say, you sorted [Apple, Blue], [Orange, Orange], [Apple, Red], this way, they would be grouped as [Apple, Blue], [Apple, Red], [Orange, Orange].

Post a Comment