comparator and comparable in java interview questions

Interview Question | Comparable vs Comparator in Java

Why We use Comparator or Comparable

First, 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.

Sorting is any process of arranging items systematically. Comparable and Comparator interfaces use Generics for compile-time type checking. Collections class provides static methods for sorting the elements of a collection. If collection elements are of a Set type, we can use TreeSet. However, we cannot sort the elements of the List. Collections class provides methods for sorting the elements of List type elements.

Let 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.

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.

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.

A 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.

Comparable Method

Method Description
public int compareTo(Object object) Compares this object with the specified object for order & return,a positive integer, if the current object is greater than the specified object.a negative integer, if the current object is less than the specified object.zero, if the current object is equal to the specified object.

Let’s simply use the previous example with this logic and avoid that annoying error.

The full source code can be found on GitHub.

A 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.

Comparator methods

Method Description
public int compare(Object obj1, Object obj2) Compares its two arguments for order.
public boolean equals(Object obj) Indicates whether some other object is “equal to” this comparator

Let’s simply use the previous example with this logic and avoid that annoying error.

Difference between Comparable and Comparator

Difference between Comparable and Comparator

Sr. No Comparable Comparator
1 Comparable provides a single sorting sequence. In other words, we can sort the collection based on a single element such as rollno, name. The Comparator provides multiple sorting sequences. In other words, we can sort the collection based on multiple elements such as rollno, name.
2 Comparable affects the original class, which means the actual class is modified. Comparator doesn’t affect the original class, which means the actual class is not modified.
3 Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.
4 Comparable is in java.lang package. The comparator is in java.util package.
5 We can sort the list elements of Comparable type by Collections.sort(List) method. We can sort the list elements of Comparator type by the Collections.sort(List, Comparator) method.

If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class. Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.

FAQ

What is the use of 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 are three differences between Comparator and comparable?

1) Comparable provides a single sorting sequence. In other words, we can sort the collection on the basis of a single element such as id, name, and price. The Comparator provides multiple sorting sequences. In other words, we can sort the collection on the basis of multiple elements such as id, name, and price etc.

What is comparable and Comparator example?

Java Comparator is an interface for sorting Java objects. Invoked by “java. util. comparator,” Java Comparator compares two Java objects in a “compare(Object 01, Object 02)” format. Using configurable methods, Java Comparator can compare objects to return an integer based on a positive, equal or negative comparison.

What is Comparator in Java?

Java Comparator is an interface for sorting Java objects. Invoked by “java. util. comparator,” Java Comparator compares two Java objects in a “compare(Object 01, Object 02)” format. Using configurable methods, Java Comparator can compare objects to return an integer based on a positive, equal or negative comparison.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *