Java Reference
In-Depth Information
Sorting Arrays
The static sort() method in the Arrays class will sort the elements of an array passed as an argument
into ascending sequence. The method is overloaded for eight of the nine types ( boolean is excluded)
we saw for the fill() method for each of two versions of sort() :
sort( type [] array)
sort( type [] array, int fromIndex, int toIndex)
The first variety sorts the entire array into ascending sequence. The second variety sorts the elements
from array[fromIndex] to array [toIndex-1] into ascending sequence. This will throw an
exception of type IllegalArgumentException if fromIndex is greater than toIndex . It will also
throw an exception of type ArrayIndexOutOfBoundsException if fromIndex is negative or
toIndex is greater than array.length .
Obviously you can pass an array of elements of any class type to the versions of the sort() method
that have the first parameter as type Object[] . If you are using either variety of the sort() method
to sort objects then the class type of the objects must support the Comparable interface since the
sort() method uses the compareTo() method to compare objects.
Here's how we can sort an array of strings:
String[] numbers = {"one", "two", "three", "four", "five",
"six", "seven", "eight"};
java.util.Arrays.sort(numbers);
After executing these statements the elements of the array numbers will contain:
"eight" "five" "four" "one" "seven" "six" "three" "two"
There are two further overloaded versions of sort() for sorting arrays of type Object[] . These are
for sorting arrays where the order of elements is determined by using an external comparator object.
The class type of the comparator object must implement the Comparator interface. One advantage of
using an external comparator for sorting a set of objects is that you can have several comparators that
can impose different orderings depending on the circumstances. For instance, in some cases you might
want to sort a name file ordering by first name within second name. On other occasions you might want
to sort by second name within first name. You can't do this using the Comparable interface
implemented by the class. The sort() methods that make use of a comparator are:
sort(Object[] array, Comparator c)
sort(Object[] array, int fromIndex, int toIndex, Comparator c)
The Comparator interface declares two methods. The equals() method is used for comparing
Comparator objects - the current Comparator object with another object of a type that also
implements the Comparator interface. It returns a boolean value indicating whether the current
object and the argument impose the same ordering on a set of objects. The compare() method in the
Comparator interface is for comparing two objects identified by the two arguments of type Object .
The method should return a negative integer, zero, or a positive integer when the first argument is less
than, equal to, or greater than the second.
Search WWH ::




Custom Search