Java Reference
In-Depth Information
When is the wildcard
<? super T>
needed? Consider the example in Listing 19.9. The
example creates a stack of strings in
stack1
(line 3) and a stack of objects in
stack2
(line 4),
and invokes
add(stack1, stack2)
(line 8) to add the strings in
stack1
into
stack2
.
GenericStack<? super T>
is used to declare
stack2
in line 13. If
<? super T>
is
replaced by
<T>
, a compile error will occur on
add(stack1, stack2)
in line 8, because
stack1
's type is
GenericStack<String>
and
stack2
's type is
GenericStack<Object>
.
<? super T>
represents type
T
or a supertype of
T
.
Object
is a supertype of
String
.
why
<? Super T>
L
ISTING
19.9
SuperWildCardDemo.java
1
public class
SuperWildCardDemo {
2
public static void
main(String[] args) {
3 GenericStack<String> stack1 =
new
GenericStack<>();
4 GenericStack<Object> stack2 =
new
GenericStack<>();
5 stack2.push(
"Java"
);
6 stack2.push(
2
);
7 stack1.push(
"Sun"
);
8 add(stack1, stack2);
9 AnyWildCardDemo.print(stack2);
10 }
11
12
public static
<T>
void
add(GenericStack<T> stack1,
13 GenericStack<?
super
T> stack2) {
14
while
(!stack1.isEmpty())
15 stack2.push(stack1.pop());
16 }
17 }
GenericStack<String>
type
<? Super T>
type
This program will also work if the method header in lines 12-13 is modified as follows:
public static
<T>
void
add(GenericStack<?
extends
T> stack1,
GenericStack<T> stack2)
The inheritance relationship involving generic types and wildcard types is summarized in
Figure 19.6. In this figure,
A
and
B
represent classes or interfaces, and
E
is a generic type
parameter.
Object
Object
? super E
E's superclass
A<?>
?
E
A<? extends B>
A<? super B>
E's subclass
? extends E
A<B's subclass>
A<B>
A<B's subclass>
F
IGURE
19.6
The relationship between generic types and wildcard types.
19.14
✓
✓
Is
GenericStack
the same as
GenericStack<Object>
?
Check
19.15
What are an unbounded wildcard, a bounded wildcard, and a lower-bound wildcard?
Point
19.16
What happens if lines 12-13 in Listing 19.9 are changed to
public static
<T>
void
add(GenericStack<T> stack1,
GenericStack<T> stack2)
Search WWH ::
Custom Search