Easy learning with example program codes

what is the difference between comparable and comparator interfaces?

Comparable interface:

Comparable interface is defined in java.lang package. It has only one method namedcompareTo(Object o).Itis used to implement natural ordering of collection elements. String and wrapper classes implements Comparable interface.


Comparator interface:

Comparator interface is defined in java.util package. It has two methods named compare(Object obj1,Object obj2) and equals(Object element).


Comparable Comparator
It provides only one sort of sequence. It provides multiple sort of sequences.
It provides one method named compareTo(). It provides one method named compare().
It is found in java.lang package. it is found in java.util package.
If we implement Comparable interface, actual class is modified. Actual class is not modified.


Java interview questions on collections

Please follow and like us:

Copyright © 2019 CodesJava Protection Status SiteMap Reference: Java Wiki