What is meant by natural ordering of objects in the context of the collections framework?
Created May 4, 2012
The objects of a class exhibit natural ordering if the class
has implemented the java.lang.Comparable interface. Such a
class must provide an implementation for the compareTo method
-- referred to as the class's natural comparison method -- that
can then be used by the algorithms and the data structures for comparing
data objects. The compareTo method must return a negative
integer, a zero, or a positive integer if the object on which it is
invoked is less than, equal to, or greater than the argument object.
It is strongly recommended that a class's natural ordering as dictated
by the implementation of the compareTo method be consistent
with equals. This consistency is achieved if and only if
e1.compareTo( (Object) e2 ) == 0 has the same boolean value as
e1.equals( (Object) e2 ) for every pair of objects e1
and e2 of the class. Lack of this consistency could elicit
strange behavior from the data structures that need to compare objects.
Many of the system supplied classes possess natural ordering. These
include String, Integer, Float, Double, Date, File and many
others. For the String class, the natural order is
lexicographic; it is chronological for the Date class;
lexicographic on the pathname for the File class, etc.