An In-Depth Exploration of Comparable and Comparator Interfaces in Java
When you need to sort or order objects in Java, there are several tools and interfaces to use for those purposes. Two key interfaces that facilitate object comparison are Comparable and Comparator interfaces. I will try to explain the interfaces in this article.
You will learn their differences and see examples of when and how to use them. But the most important point can be when it might be best to avoid them. Along the way, you will see detailed code examples to illustrate a few use cases.
If you don’t have a medium membership, you can use this link to reach the article without a paywall.
1.1 Comparable Interface
The Comparable
interface is a fundamental part of Java's standard library, residing in the java.lang
package. It defines only compareTo
method which allows objects of a class to be compared to one another. You enable instances of your class to be sorted in a natural order by implementing Comparable
public interface Comparable<T> {…