Java Reference
In-Depth Information
L
ISTING
19.2
GenericMethodDemo.java
1
public class
GenericMethodDemo {
2
public static void
main(String[] args ) {
3 Integer[] integers = {
1
,
2
,
3
,
4
,
5
};
4 String[] strings = {
"London"
,
"Paris"
,
"New York"
,
"Austin"
};
5
6 GenericMethodDemo.<Integer>print(integers);
7 GenericMethodDemo.<String>print(strings);
8 }
9
10
public static
<E>
void
print(E[] list) {
11
for
(
int
i =
0
; i < list.length; i++)
12 System.out.print(list[i] +
" "
);
13 System.out.println();
14 }
15 }
generic method
To declare a generic method, you place the generic type
<E>
immediately after the keyword
static
in the method header. For example,
declare a generic method
public static
<E>
void
print(E[] list)
To invoke a generic method, prefix the method name with the actual type in angle brackets.
For example,
invoke generic method
GenericMethodDemo.<Integer>print(integers);
GenericMethodDemo.<String>print(strings);
or simply invoke it as follows:
print(integers);
print(strings);
In the latter case, the actual type is not explicitly specified. The compiler automatically dis-
covers the actual type.
A generic type can be specified as a subtype of another type. Such a generic type is
called
bounded
. For example, Listing 19.3 revises the
equalArea
method in Listing 13.4,
TestGeometricObject.java, to test whether two geometric objects have the same area. The
bounded generic type
<E extends GeometricObject>
(line 7) specifies that
E
is a generic
subtype of
GeometricObject
. You must invoke
equalArea
by passing two instances of
GeometricObject
.
bounded generic type
L
ISTING
19.3
BoundedTypeDemo.java
1
public class
BoundedTypeDemo {
2
public static void
main(String[] args ) {
3 Rectangle rectangle =
new
Rectangle(
2
,
2
);
4 Circle circle =
new
Circle(
2
);
5
6 System.out.println(
"Same area? "
+
7 equalArea(rectangle, circle));
8 }
9
10
public static
<E
extends
GeometricObject>
boolean
equalArea(
11 E object1, E object2) {
12
Rectangle
in Listing 13.3
Circle
in Listing 13.2
bounded generic type
return
object1.getArea() == object2.getArea();
13 }
14 }
Search WWH ::
Custom Search