Java FAQ: Top Questions
22. What is the Comparable and Comparator interfaces?
Comparable
and
Comparator
are interfaces in Java used for sorting objects, defined in
java.lang
and
java.util
, respectively.
-
Comparable:
-
Implemented by a class to define its natural ordering (e.g.,
String
,Integer
). -
Has one method:
compareTo(T o)
. -
Used by
Collections.sort
orArrays.sort
.
-
Implemented by a class to define its natural ordering (e.g.,
-
Comparator:
- A separate class or lambda for custom sorting.
-
Has method:
compare(T o1, T o2)
. - Provides flexibility for multiple sorting criteria without modifying the class.