Programming





Difference between Comparable and Comparator

Difference between Comparable and Comparator


by Administrator | 21-Mar-2020
Java

Tags:  Comparable  Comparator  Difference

Share: 


Comparable

Comparator

Available in java.lang package

Available in java.util package

This interface has only one method which is compareTo()

This method compares this object with o1 object and returns an integer. Its value has the following meaning:

1. positive – this object is greater than o1

2. zero – this object equals to o1

3. negative – this object is less than o1

 

This interface has two methods which are compare() and equals()

compare() method compares two objects o1 and o2 and returns an integer. Its value has the following meaning.

1. positive – o1 is greater than o2

2. zero – o1 equals to o2

3. negative – o1 is less than o1

 

It is meant for default natural sorting order

It is meant for customized sorting order

All wrapper classes and String class implement comparable interface

Collator and RuleBasedCollator are the only classes to implement comparator interface

Sorting logic must be in the same class whose objects are being sorted. Hence this is called natural ordering of objects

Sorting logic is in a separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id, name, etc

Collections.sort(List) method can be used for sorting the list based on default natural sorting order

Collections.sort(List, Comparator) method is used to sort the list using Comparator.


Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.