Java Comparable vs Comparator
In this articles we will discuss Java Comparable vs Comparator, often people have lots of questions when it comes to Java Comparable vs Comparator
- What is Comparable and what is Comparator in Java
- How do we use them
- What is the difference between Comparable and Comparator?
- When we should use Comparable vs Comparator
This post does not cover basics about Java’s Comparable and Comparator (Will cover that in another post), but this post is more towards getting insight about Comparable vs Comparator.
public interface Comparable<T>
When a class implement Comparable, the compareTo method of the class defines the “natural” ordering of that object. CompareTo method should follow general contracts, few of the examples are
- Should always be returned 0 for objects when equal () comparisons return true.
- Comparable is useful when there’s a single natural default comparison.
public Interface Comparator<T>
Comparator provides a way to compare 2 objects and can compare objects in a way that might not align with the natural ordering.
One of the common examples is String, String is generally compared alphabetically, ” a”.compareTo(“b”) would use alphabetical comparisons.If you want to compare based on the String length, writing custom Comparator is a preferred solution.
If you do not have control over the source code ( where you can not implement Comparable ), then use Comparator.Comparator is useful when you have multiple ways to compare an object ( e.g you can compare cars by brand and cc etc.).
Both seem to be different, but to summarise, there isn’t much difference.Both ends to similar means. Implement comparable for natural order, and write a comparator for other sorting or comparison needs.
Please read Java Sorting Example(Comparable and Comparator) to get an understanding of using Comparable and Comparator for sorting objects in Java.