I happen to come across many statements like Comparable
is used when natural ordering is required while sorting an array or collection and Comparator
for total ordering.
The version you may have heard could be same or different with the same meaning but ultimately its one of the distinguishing factors between the two (Comparator
and Comparable
interfaces).
But, I couldn't find a difference between the two types of ordering anywhere. I'd appreciate if someone could explain it with a good example :)
Total ordering means all values can be compared to all other values. For example, if you have a collection of BigDecimal
and String
there is no natural total order (but you could invent one)
In Java, the Natural order is defined as the ordering provided by the JVM. This might not match what a people might believe is the natural order. e.g. Strings are sorted ASCIIbetically. Meaning an uppercase Z
comes before a lowercase a
and 10
is before 2
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.