Java Reference
In-Depth Information
35 /** Sort an array of comparable objects */
36 public static <E extends Comparable<E>> void sort(E[] list) {
37 E currentMin;
38
generic sort method
int currentMinIndex;
39
40 for ( int i = 0 ; i < list.length - 1 ; i++) {
41 // Find the minimum in the list[i+1..list.length-2]
42 currentMin = list[i];
43 currentMinIndex = i;
44
45 for ( int j = i + 1 ; j < list.length; j++) {
46 if (currentMin.compareTo(list[j]) > 0 ) {
47 currentMin = list[j];
48 currentMinIndex = j;
49 }
50 }
51
52 // Swap list[i] with list[currentMinIndex] if necessary;
53 if (currentMinIndex != i) {
54 list[currentMinIndex] = list[i];
55 list[i] = currentMin;
56 }
57 }
58 }
59
60 /** Print an array of objects */
61 public static void printList(Object[] list) {
62 for ( int i = 0 ; i < list.length; i++)
63 System.out.print(list[i] + " " );
64 System.out.println();
65 }
66 }
compareTo
Sorted Integer objects: 2 3 4
Sorted Double objects: -22.1 1.3 3.4
Sorted Character objects: J a r
Sorted String objects: Kim Susan Tom
The algorithm for the sort method is the same as in Listing 7.8, SelectionSort.java. The
sort method in that program sorts an array of double values. The sort method in this
example can sort an array of any object type, provided that the objects are also instances of
the Comparable interface. The generic type is defined as <E extends Comparable<E>>
(line 36). This has two meanings. First, it specifies that E is a subtype of Comparable . Second,
it specifies that the elements to be compared are of the E type as well.
The sort method uses the compareTo method to determine the order of the objects in
the array (line 46). Integer , Double , Character , and String implement Comparable ,
so the objects of these classes can be compared using the compareTo method. The program
creates arrays of Integer objects, Double objects, Character objects, and String objects
(lines 4-16) and invoke the sort method to sort these arrays (lines 19-22).
19.10
Given int[] list = {1, 2, -1} , can you invoke sort(list) using the sort
method in Listing 19.4?
Check
Point
19.11
Given int[] list = {new Integer(1), new Integer(2), new Inte-
ger(-1)} , can you invoke sort(list) using the sort method in Listing 19.4?
 
 
Search WWH ::




Custom Search