Objects that have an ordering are compared using the compareTo() method.
15. Integer Sorting Program
Integer Sorting Program
Here is a picture of an ordered array. Each cell of the array holds a reference to a
String. The order of the
Strings is determined by the values returned by the
compareTo() method for
For any two strings
X.compareTo(Y) is negative, then
X is left of
Y in the ordered array.
For an array of object references, the
sort() method automatically uses the
compareTo() method of the class of objects being sorted. The class must implement the
Comparable interface (and so must have a
static void sort( Object a )
- // Sorts the array a into ascending order,
// Each cell of the array must refer to an object
// (must not be null).
If not all cells of the array are filled, use
static void sort( Object a,
int fromIndex, int toIndex )
// Sorts the array a into ascending order,
// as determined by the values compareTo() returns.
// Only the cells between the two indexes are sorted.
// Each of those cells must refer to an object.