Java Reference
In-Depth Information
Note
An unbounded generic type <E> is the same as <E extends Object> .
Note
To define a generic type for a class, place it after the class name, such as
GenericStack<E> . To define a generic type for a method, place the generic type
before the method return type, such as <E> void max(E o1, E o2) .
generic class parameter vs.
generic method parameter
19.8
How do you declare a generic method? How do you invoke a generic method?
Check
19.9
What is a bounded generic type?
Point
19.5 Case Study: Sorting an Array of Objects
You can develop a generic method for sorting an array of Comparable objects.
Key
Point
This section presents a generic method for sorting an array of Comparable objects. The
objects are instances of the Comparable interface, and they are compared using the
compareTo method. To test the method, the program sorts an array of integers, an array of
double numbers, an array of characters, and an array of strings. The program is shown in
Listing 19.4.
L ISTING 19.4
GenericSort.java
1 public class GenericSort {
2 public static void main(String[] args) {
3 // Create an Integer array
4 Integer[] intArray = { new Integer( 2 ), new Integer( 4 ),
5
new Integer( 3 )};
6
7 // Create a Double array
8 Double[] doubleArray = { new Double( 3.4 ), new Double( 1.3 ),
9
new Double( -22.1 )};
10
11 // Create a Character array
12 Character[] charArray = { new Character( 'a' ),
13
new Character( 'J' ), new Character( 'r' )};
14
15 // Create a String array
16 String[] stringArray = { "Tom" , "Susan" , "Kim" };
17
18
// Sort the arrays
19
sort(intArray);
sort Integer objects
sort Double objects
sort Character objects
sort String objects
20
sort(doubleArray);
21
sort(charArray);
22
sort(stringArray);
23
24 // Display the sorted arrays
25 System.out.print( "Sorted Integer objects: " );
26 printList(intArray);
27 System.out.print( "Sorted Double objects: " );
28 printList(doubleArray);
29 System.out.print( "Sorted Character objects: " );
30 printList(charArray);
31 System.out.print( "Sorted String objects: " );
32 printList(stringArray);
33 }
34
 
 
 
Search WWH ::




Custom Search