The comparable and Comparator are two interfaces provided by Java Core API. They used to compare stuff in some way for sorting and ordering objects in Java. But what they exactly are and what is different between them? In this tutorial we will see their usage.
Comparable interface has only one method called compareTo and its purpose is to define the natural ordering of an object. Specifically, compareTo() method should need to return an integer as follows:
- a negative integer (–1) if this object is less than the specified object
- a positive integer (1) if this object is greater than the specified object
- zero integer (0) if this object is equal to specified object
For example consider the real case where we have a Name class:
Comparator interface gives you the capability to sort a given collection any number of different ways to pas to methods such as Collections.sort() or Arrays.sort(). So you might want to create a Comparator object for the following ideas.
- To provide service different ways to sort your objects.
- To provide comparison methods for classes that you cannot modify or no control over such String, Date …
- To implement strategy pattern for representing an algorithm in which situation to be used.
Sometimes, to write the comparaTo() or compare() methods are very bored and the code will also not be readable. Guava ComparisonChain allows you to check whether an object is less-than or greater-than another object by comparing multiple properties. It should be used the both of Comparable and Comparator.