I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?
If you see then logical difference between these two is Comparator
in Java compare two objects provided to him, while Comparable
interface compares "this" reference with the object specified.
Comparable
in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable
interface.
If any class implement Comparable
interface in Java then collection of that object either List
or Array
can be sorted automatically by using Collections.sort()
or Array.sort()
method and object will be sorted based on there natural order defined by compareTo
method.
Objects which implement Comparable
in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet
, without specifying any Comparator
.