Java Reference
In-Depth Information
10.10.3 Arrays.sort() and Arrays.binarySearch()
The sort methods for the primitive types look like:
void sort ( type [] array)
void sort ( type [] array, int fromIndex, int toIndex)
There is a sort method for each primitive type except boolean . The elements in
the array are sorted in ascending order using a variant of the QuickSort algorithm.
(See the Java 2 API Specifications for the java.util.Arrays class for details.)
The second version sorts those elements between the given indices.
For sorting Object types, there are two approaches. For the first approach
there are two methods available:
void sort (Object[] array)
void sort (Object[] array, int fromIndex, int toIndex)
Here the objects are sorted into ascending order using the “natural ordering” of the
elements. The array elements must implement the java.lang.Comparable
interface and provide the method
int compareTo (Object)
This method defines the “natural ordering” such that comparing object x to y
results in a negative number if x is lower than y (on a scale that makes sense for
the class), equal to 0 if the objects are identical, and a positive number if x is
greater than y. Your compareTo() method must be written to return a negative,
zero, or positive integer according to the ordering rules that make sense for the
nature of the objects that the class describes.
Forexample,
MyClass my - class1 = someMethodThatBuildsAMyClassInstance ();
MyClass my - class2 =
someMethodThatBuildsADifferentMyClassInstance ();
// Now compare the two instances of MyClass
if (my - class1.compareTo (my - class2) < 0)
System.out.println ( " my - class1 is ' less than ' my - class2 " );
else if (my - class1.compareTo (my - class2) == 0)
System.out.println ( " my - class1 is ' equal to ' my - class2 " );
else
System.out.println (
" my - class1 is ' greater than ' my - class2 " );
For the alternative approach to comparing Object arrays, you create an auxiliary
class that implements the java.util.Comparator interface and that knows
how to compare and order two objects of interest. This technique is particularly
Search WWH ::




Custom Search