Java Reference
In-Depth Information
Fig. 20.1 (lines 14, 16 and 18) and the outputs of the two applications are identical. This
demonstrates the expressive power of generics.
1
// Fig. 20.3: GenericMethodTest.java
2
// Printing array elements using generic method printArray.
3
4
public
class
GenericMethodTest
5
{
6
public static void
main(String[] args)
7
{
8
// create arrays of Integer, Double and Character
9
Integer[] intArray = {
1
,
2
,
3
,
4
,
5
};
10
Double[] doubleArray = {
1.1
,
2.2
,
3.3
,
4.4
,
5.5
,
6.6
,
7.7};
11
Character[] charArray = {
'H'
,
'E'
,
'L'
,
'L'
,
'O'
};
12
13
System.out.printf(
"Array integerArray contains:%n"
);
14
printArray(integerArray);
// pass an Integer array
15
System.out.printf(
"%nArray doubleArray contains:%n"
);
16
printArray(doubleArray);
// pass a Double array
17
System.out.printf(
"%nArray characterArray contains:%n"
);
18
printArray(characterArray);
// pass a Character array
19
}
20
21
// generic method printArray
public
static
<T>
void
printArray(T[] inputArray)
22
23
{
24
// display array elements
for
(T element : inputArray)
System.out.printf(
"%s "
, element);
25
26
27
28
System.out.println();
29
}
30
}
// end class GenericMethodTest
Array integerArray contains:
1 2 3 4 5 6
Array doubleArray contains:
1.1 2.2 3.3 4.4 5.5 6.6 7.7
Array characterArray contains:
H E L L O
Fig. 20.3
|
Printing array elements using generic method
printArray
.
Type Parameter Section of a Generic Method
Line 22 begins method
printArray
's declaration. All generic method declarations have a
type-parameter section
(
<T
> in this example) delimited by
angle brackets
that precedes
the method's return type. Each type-parameter section contains one or more
type param-
eters
, separated by commas. A type parameter, also known as a
type variable
, is an identi-
fier that specifies a generic type name. The type parameters can be used to declare the
return type, parameter types and local variable types in a generic method declaration, and