Comparable and Comparator in Java

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

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:

  1. a negative integer (–1) if this object is less than the specified object
  2. a positive integer (1) if this object is greater than the specified object
  3. 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

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.

  1. To provide service different ways to sort your objects.
  2. To provide comparison methods for classes that you cannot modify or no control over such String, Date …
  3. 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.

1 comment:

  1. To understand the
    difference between using methods comparable vs comparator java https://explainjava.com/comparable-comparator-java/ I found a special tutorial in
    Java and learned the details of the comparison as a whole. Theoretically, this is a slightly different explanation but meaning, as I have managed to understand, the same. After all, I advised my colleagues this lesson because I used it myself. And your method also is quite simple and understandable, thank u.