Wednesday, 19 February 2014

Comparable and compareTo Method


Comparable has only one method compareTo(), which is where we define logic to compare objects. As I said in previous paragraph that this method returns positive, negative and zero depending upon result of comparison, but most important thing, there is no restriction on return 1, 0 or -1 for greater, equal and lesser results, you can return any positive or negative number, this property is utilized in this example, but it comes with caveat that difference between them should not exceed, Integer.MAX_VALUE, well explained in my favourite book Effective Java. There are few more things, you need to consider while implementing Comparable interface. Before Java 5, its compareTo() method accepts java.lang.Object, but after introduction of Generics, this class can be written in standard type T. This makes it type-safe with compiler helping you by flagging error, when you pass different object to compareTo(). So always use generic version. Second thing, make sure your compareTo() is consistent with equals() method. Though this is not a requirement mandated by compiler or Java API, and there are examples of violating this principle in Java API itself e.g. BigDecimal, you should make them consistent if you are going to store object in SortedSet or SortedMap. Failing to do so, will result in classes like Set breaking their invariants and allowing duplicates. One more important thing to remember is order of comparison, if your object contains multiple value fields then the order on which you compare is important, compare them from most useful to least useful. This is where it differs with equals, in that you don't need to put attention on order of comparison, though comparing primitives earlier is preferred due to performance reason, but here it affects your sorting order. If you are comparing objects, then call their respective compareTo() methods, don't reinvent comparison. Last but not the least Prefer relational operator over arithmetic operator for comparing numeric fields.

No comments:

Post a Comment