Categories

  • articles

Tags

  • java

Implementing the Comparable interface in Java give the object a natural ordering, as in makes it Sortable. The comparable interface only has one method:

public interface Comparable {
	int compareTo(T t);
}

CompareTo only requires a output of negative integer, zero or positive integer representing less than, equals to, or greater than. Also be aware that if object returns a compareTo value of 0 (Equals to) it is not the same as calling equals on the object. For example new BigDecimal(“5.0”) and new BigDecimal(“5.00”) returns false on equals but 0 on compareTo!

When comparing multiple fields it is important to remember the order you compare them, start with the most significant fields! Below is a example of how to implement compareTo:

public class TestClass implements Comparable<TestClass> {
    int id;
    int value01;
    int Date value02;

    // Left out constructor, getters, hashCode, equals

    @Override
    public int compareTo(TestClass o) {
        if (this == o)
            return 0;

        int diff = id - o.id;
        if (diff != 0)
            return diff;

        diff = value01 - 0.value01;
        if (diff != 0)
            return diff;

        if (value02 == null) {
            if (o.value02 == null) {
                return 0
            }
            return -1;
        }
        if (0.value02 == null) {
            return 1;
        }
        return value02.compareTo(o.value02);
    }
}