Hey, Tea Lovers! Today let’s look at the most asked interview question, Comparable vs Comparator. Both beginners and experienced persons get this question in their interviews. This post is one of the many in the series of Interview Questions, where we don’t just hang you with one line answer, rather try to explain it so that it gets fit into your head. Show
You can follow me on social media via @coderstea on Twitter, Linkedin, Facebook, or Instagram. We also share high-quality videos about programming on our Youtube channel. You can also publish your post on CodersTea, just share your thought on Contact Us or let us know in the comments. I know you are in a hurry to prepare for the interview, so I will make this post as short as possible, So prepare your cup of tea to sip and code. Why We use Comparator or ComparableFirst, we need to understand why comparable & comparator comes into the picture. They give you the answer of comparison. Like, which one is greater which one is smaller. And the main reason for doing that is to Sort the collection of objects. We can easily compare the Integer or String naturally, but the complex or regular POJO object has multiple fields. In that case, we need to specify how we are determining which objects should come first or which one is greater. In java String and Wrapper classes had implemented the Comparable interface. So if you store string or wrapper class objects then it will be used Comparable & get Sorted. SortingSorting is any process of arranging items systematically. Comparable and Comparator interfaces use Generics for compile-time type checking. Example of SortingLet understand with a coding example, First, we will sort int, String & List then after we create one custom Student class and try to understand what was the issue. The full source code can be found on GitHub. Code
Output
As above console output, we can see that with java inbuild primitive & wrapper class the sorting working properly, let see the same with a custom class. Custom class Code example.Code
Output
Here is a problem, When you try to run this, it throws the runtime exception as the Student class cannot be cast to class java.lang.Comparable. Because when JVM tried to sort custom class, it starts the search the logic for comparing this custom class. Since you didn’t define any, it throws the Exception. Now let us look at the ways to implement this logic. ComparableA Comparable interface in java.lang package is used to order the objects of the user-defined class. It contains only one method named compareTo(Object object) A Comparable object is capable of comparing itself with another object. It provides a single comparison only, meaning all comparisons are tied to one specific logic only. You can’t scale with multiple sorting methods depending on the requirement.
Let’s simply use the previous example with this logic and avoid that annoying error. CodeThe full source code can be found on GitHub.
Output
ComparatorA Comparator interface is used to order the objects of a user-defined class. This interface is under java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element). The biggest advantage of the Comparator is that it is pluggable. With this, unlike Comparable, you have the flexibility to add as much comparison logic as you want. Simply create an object by implementing a Comparator and passing it to the sorting method. And since Java 8’s lambda showed up, a one-liner is all you need. The Comparator interface has many methods, the below are required frequently. to get a full list click here.
Let’s simply use the previous example with this logic and avoid that annoying error. Code
Output
Difference between Comparable and Comparator
When to Use What, and WhyLet us look at When to use what, where, and how… When to Use Comparable
For example, String and Integer and other Wrapper classes, they by-default implement comparable to us the natural comparison of the types. So we don’t need to write logic. When to Use ComparatorThe Comparator provides multiple sorting sequences. In other words, we can sort the collection based on multiple elements such as rollno, name. Due to this, the Comparator is very useful. It is used widely as it below example you can see that all application is added only due to this feature.
In many cases, we are not able to modify the source code to make our comparison. For example, the Integer class already provided a logic but if you want to provide some custom logic for sorting, we can do so with Comparator.
The best-case scenario for Comparator is when we have different comparison logic for various fields and want to sort something based on requirements. ConclusionThat’s it for this post. We looked at what is Comparable and Comparator, the differences between them, and many more tips on when and what to use. This post is one of the many in the series of Interview Questions, where we don’t just hang you with one line answer, rather try to explain it so that it gets fit into your head. You can learn more about other Java features such as Stream API, Best Practices, Functional Programming. The full source code can be found on GitHub and the Full project is available here. Please feel free to suggest any changes, such as additional info, or if you have any questions on some points let us know in the comments. We will be happy to help you. See you in the next post. HAKUNA MATATA!!!
RelatedWhat is difference between Comparator and comparable in Java?Comparator in Java is used to sort attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator in Java compares two different class objects provided. Comparable is present in java.
What is the difference between Comparator vs comparable?While Comparable is used on objects that are naturally ordered, the Comparator interface implements sorting by taking the attributes of an object into consideration. Further, Comparator sorting takes into account objects of two different classes and Comparable compares objects using the “this” reference.
Can we use both comparable and Comparator in Java?Yes we can extend any pojo class to implement both comparable and comparator interface and implement the methods defined by them. I implemented it in sample Student POJO class. When called Collections.
Why do we use comparable and Comparator in Java?Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting. For using Comparable, Class needs to implement it whereas for using Comparator we don't need to make any change in the class. Comparable interface is in java.
|