Comparable vs Comparator interface in Java



Comparable and Comparator both are interfaces and can be used to sort collection elements.
There are many differences between Comparable and Comparator interfaces that are mentioned as follows:

Comparable in JavaComparator in Java
Comparable interface is used to sort the objects with natural ordering.Comparator in Java is used to sort attributes of different objects.
Comparable interface compares “this” reference with the object specified.Comparator in Java compares two different class objects provided.
Comparable is present in java.lang package.

A Comparator is present in the java.util package.
Comparable affects the original class, i.e., the actual class is modified.Comparator doesn’t affect the original class
Comparable provides compareTo() method to sort elements.Comparator provides compare() method, equals() method to sort elements.

This question is one of the most frequently asked questions in interviews.
Comparable vs Comparator interface in Java Comparable vs Comparator interface in Java Reviewed by 13thGhost on 9:35 PM Rating: 5

No comments:

Recommended Posts

Powered by Blogger.