In Java when it comes to sort any collections,comparable and comparator comes into picture.Comparable and Comparator are two interfaces provided by Java Core API.Here we will take a look into why Comparable and Comparator are used for sorting though there are inbuilt methods provide by Java API to sort primitive types array or Wrapper classes array or list.What are the use cases to choose Comparable for sorting and in which scenario Comparator should be preferred.Now, let's see how to use Comparator and Comparable in Java with example.
The Comparable interface is used by the Collections.sort() method and the java.util.Arrays.sort() method to sort the Lists and arrays of objects respectively.At first, let's quickly look into a simple example and will discuss more about it.
Here the Employee class implements Comparable and overrides it's compareTo() method to sort the employee object based on it's name.
Now if you have a collection of employee objects then it can be used as below for sorting:
The Comparator interface gives us the capability to sort a given collection any number of different ways.The other important capability is that we can use it to sort instances of those classes which we can't modify, unlike the Comparable interface, which forces to change the source code of class which we want to sort.Let us take a quick example.
To sort the collection of employee :
1. In case of Comparable sorting logic must be in same class whose objects are being sorted.Hence, restricts to sort a given collection by single attribute.Whereas, in case of Comparator, sorting logic is defined in seperate class.Hence, we can write different sorting based on different attributes of objects to be sorted.
2. Class whose objects to be sorted must implement Comparable interface.In case of Comparator, class whose objects to be sorted do not need to implement this interface.
I hope this article served you that you were looking for. If you have anything that you want to add or share then please share it below in the comment section.
Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.
Contact us: email@example.com