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:
- 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
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.
To understand the
ReplyDeletedifference 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.