Possible Duplicate:
Java: What is the difference between implementing Comparable and Comparator?
Difference between comparable interface and comparator interface and where to use?example?
Possible Duplicate:
Java: What is the difference between implementing Comparable and Comparator?
Difference between comparable interface and comparator interface and where to use?example?
Comparable
makes an object intrinsically comparable to other objects.
Comparator
allows to implement external comparison logic, which can be applied to objects that are not Comparable
, or that require different logic from their default comparison logic.
For example, you have Collections.sort(list)
, which can sort only lists of objects that implement Comparable
, while there is another method - Collections.sort(list, comparator)
, by which you can sort any list.
In conceptual sense, a Comparator is the "comparison operator", i.e. the logic, used to determine whether a Comparable is greater/lesser than another Comparable.
PS: I'm using the term "operator" in comparison operator rather loosely; as they're not operator as in having symbols (e.g. <) syntactically assigned to the operations.
In a more practical sense, a Comparable allows an Object to determine how to compare itself with another Object. While Comparator allows the programmer to determine how to compare two Objects.