Comparable and Comparator

One of the most important topics in java comparable and comparator. Both are interface in java and used to compare the objects. In this post, we will discuss all the detail of java comparable and comparator.

Here is the table content of the article will we will cover this topic.
1. What is the Comparator interface in Java?
2. Why we use Comparator?
3. How to use it?

4. What is the Comparable interface in Java?
5. Why we use comparable?
6. How to use it?

7. How comparable useful over Comparator?
8. How Comparator useful over comparable?
9. Why Comparable and Comparator are useful?
10. Difference between comparable and comparator?

java comparable and comparator

What is the Comparator in java?

It is an interface that can be used to sort collection elements. This interface is found in java.util package and contains two methods compare(Object obj1, Object2 obj) and equals(Object obj). It imposes the order of all the objects of a class that implements it. Comparator interface is used to order the objects of a user-defined class.

By use of Comparator interface, Object can compare itself with another object. You can provide a multiple sorting sequence. It means you can compare the Objects of class based on multiple data members. We will discuss it in detail and see how we can use it?

What is Comparable in java?

It is an interface that can be used to sort collection elements. This interface is found in java.lang package and contains only one method named compareTo(Object). It imposes the order of all the objects of a class that implements it.

NOTE: All the Wrapper classes implement the Comparable interface by default.

By use of Comparable interface, Object can compare itself with another object. You can provide a single sorting sequence only. It means you can compare the Objects of class based on single data members only. We will discuss it in detail and see how we can use it?

Leave a Comment