COMPARABLE VS COMPARATOR
In this article, I will be explaining why java came up with COMPARATOR in the latest versions even though it already has a COMPARABLE interface
You can find small code snippets along the way for better understanding.
Let's dive into the article
Whenever we are designing the class, we will have some idea of what variables we need to store as part of this class
Similarly, if we also know how to sort that object then we will implement the Comparable interface and we will override the compareTo method
In that compareTo method, we will be writing the sort logic whether it should return 1, -1, or 0, and based on that we will sort elements in the objects
In the future for some reason, if we want to sort the movie object based on the name, we can't achieve that because we can only have one compareTo method within the movie object
In such cases to solve the problem we came up with the Comparator interface
This interface has a compare method that can be written exclusively for that specific variable with which we want to sort
I hope the above code snippets helped you in understanding why comparator is brought into the picture, If you still have any doubts or suggestions, please comment below.
Comments
Post a Comment