Java Comparable vs Comparator

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

  1. What is Comparable and what is Comparator in Java
  2. How do we use them
  3. What is the difference between Comparable and Comparator?
  4. 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.

 

Comparable

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

  1. Should always be returned 0  for objects when equal ()  comparisons return true.
  2. Comparable is useful when there’s a single natural default comparison.

 

 

Comparator

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.

Java Development Journal

Hello!! Welcome to the Java Development Journal. We love to share our knowledge with our readers and love to build a thriving community.

follow me on:

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of