Chapter 17: java.util Part 1: The Collections Framework 483
Here,arrayis the array to be sorted. In the last form,cis aComparatorthat is used to order
the elements ofarray.The last two forms can throw aClassCastExceptionif elements of the
array being sorted are not comparable.
The second version ofsort( )enables you to specify a range within an array that you want
to sort. Its forms are shown here:
static void sort(bytearray[ ], intstart, intend)
static void sort(chararray[ ], intstart, intend)
static void sort(doublearray[ ], intstart, intend)
static void sort(floatarray[ ], intstart, intend)
static void sort(intarray[ ], intstart, intend)
static void sort(longarray[ ], intstart, intend)
static void sort(shortarray[ ], intstart, intend)
static void sort(Objectarray[ ], intstart, intend)
static <T> void sort(Tarray[ ], intstart, intend, Comparator<? super T>c)
Here, the range beginning atstartand running throughend–1 within arraywill be sorted.
In the last form,cis aComparatorthat is used to order the elements ofarray.All of these
methods can throw anIllegalArgumentExceptionifstartis greater thanend,or an
ArrayIndexOutOfBoundsExceptionifstartorendis out of bounds. The last two forms can
also throw aClassCastExceptionif elements of the array being sorted are not comparable.
Arraysalso overridestoString( )andhashCode( )for the various types of arrays. In
addition,deepToString( )anddeepHashCode( )are provided, which operate effectively on
arrays that contain nested arrays.
The following program illustrates how to use some of the methods of theArraysclass:
// Demonstrate Arrays
import java.util.*;
class ArraysDemo {
public static void main(String args[]) {
// Allocate and initialize array.
int array[] = new int[10];
for(int i = 0; i < 10; i++)
array[i] = -3 * i;
// Display, sort, and display the array.
System.out.print("Original contents: ");
display(array);
Arrays.sort(array);
System.out.print("Sorted: ");
display(array);
// Fill and display the array.
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
display(array);
// Sort and display the array.
Arrays.sort(array);
System.out.print("After sorting again: ");
display(array);