Monday, May 17, 2021

Comparable vs Comparator

 

Comparable

Comparator

Comparable provides compareTo() method to sort elements in Java.

Comparator provides compare() method to sort elements in Java.

Comparable interface is present in java.lang package.

Comparator interface is present in java.util package.

The logic of sorting must be in the same class whose object you are going to sort.

The logic of sorting should be in separate class to write different sorting based on different attributes of objects.

The class whose objects you want to sort must implement comparable interface.

Class, whose objects you want to sort, do not need to implement a comparator interface.

It provides single sorting sequences.

It provides multiple sorting sequences.

This method can sort the data according to the natural sorting order.

This method sorts the data according to the customized sorting order.

It affects the original class. i.e., actual class is altered.

It doesn't affect the original class, i.e., actual class is not altered.

Implemented frequently in the API by: Calendar, Wrapper classes, Date, and String.

It is implemented to sort instances of third-party classes.

All wrapper classes and String class implement comparable interface.

The only implemented classes of Comparator are Collator and RuleBasedCollator.

The person who is writing the class is responsible to implement & define natural sorting order for a class e.g. empID for Employee, username for User, etc.

The person using the class, if not satisfied with the natural sorting order available for the class OR if natural sorting order is not available, can use comparator for that class


Additional note:

public static Comparator reverseOrder()

Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface. (The natural ordering is the ordering imposed by the objects’ own compareTo method.)

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...