Java Reference
In-Depth Information
Working with Arrays
The exam objectives state that you should be able to sort arrays either in their natural order
or using a Comparator object. The exam also requires knowledge of performing
a binary search on arrays. These objectives are indirectly referring to the static sort and
binarySearch methods of the java.util.Arrays class. We start with a discussion on
sorting arrays.
Sorting Arrays
The Arrays class contains a collection of sort methods for sorting arrays of primitive types
and objects. There is a pair of sort methods for each Java array type (except arrays of
boolean s). For example, the following sort methods are for sorting arrays of ints :
public static void sort(int[] a)
public static void sort(int[] a, int fromIndex, int toIndex)
Similarly, there are two sort methods for byte , short , long , float , double , and char
arrays. The overloaded versions of sort allow for sorting a subset of the given array.
There is also a pair of sort methods for Object arrays:
public static void sort(Object[] a)
public static void sort(Object[] a, int fromIndex, int toIndex)
The Object array is sorted in its natural order and the elements in the array must
implement Comparable and be mutually comparable.
The Arrays class also contains a generics version of sort that uses a Comparator to
determine the ordering:
public static <T> void sort(T[] a, Comparator<? super T> c)
public static <T> void sort(T[] a, int fromIndex, int toIndex, Comparator<?
super T> c)
Similar to sorting lists, a Comparator is useful when the objects being sorted do not
implement Comparable or you need the objects sorted in a different order than their natural
ordering.
Passing an array to a sort method alters the array. The values are rearranged in the
appropriate order. Let's start with an example that sorts an array of primitive types. Study
the following code and see if you can determine what it does:
6. int [] values = new int[15];
7. System.out.print(“Initial values: “);
8. for(int i = 0; i < values.length; i++) {
9. values[i] = (int) (Math.random() * 10);
10. System.out.print(values[i] + “ “);
11. }
Search WWH ::




Custom Search