Java Reference
In-Depth Information
7
return o2;
8 }
9 }
If you invoke the max method using
// 23 is autoboxed into new Integer(23)
MaxUsingGenericType.max( "Welcome" , 23 );
a compile error will be displayed, because the two arguments of the max method in
MaxUsingGenericType must have the same type (e.g., two strings or two integer objects).
Furthermore, the type E must be a subtype of Comparable<E> .
As another example, in the following code you can declare a raw type stack in line 1,
assign new GenericStack<String> to it in line 2, and push a string and an integer object
to the stack in lines 3 and 4.
1 GenericStack stack;
2 stack = new GenericStack<String>();
3 stack.push( "Welcome to Java" );
4 stack.push( new Integer( 2 ));
However, line 4 is unsafe because the stack is intended to store strings, but an Integer object
is added into the stack. Line 3 should be okay, but the compiler will show warnings for both
line 3 and line 4, because it cannot follow the semantic meaning of the program. All the com-
piler knows is that stack is a raw type, and performing certain operations is unsafe. Therefore,
warnings are displayed to alert potential problems.
Tip
Since raw types are unsafe, this topic will not use them from here on.
19.12 What is a raw type? Why is a raw type unsafe? Why is the raw type allowed in Java?
19.13 What is the syntax to declare an ArrayList reference variable using the raw type
and assign a raw type ArrayList object to it?
Check
Point
19.7 Wildcard Generic Types
You can use unbounded wildcards, bounded wildcards, or lower-bound wildcards to
specify a range for a generic type.
Key
Point
What are wildcard generic types and why are they needed? Listing 19.7 gives an example to
demonstrate the needs. The example defines a generic max method for finding the maximum
in a stack of numbers (lines 12-22). The main method creates a stack of integer objects, adds
three integers to the stack, and invokes the max method to find the maximum number in the
stack.
L ISTING 19.7
WildCardNeedDemo.java
1 public class WildCardNeedDemo {
2 public static void main(String[] args ) {
3 GenericStack<Integer> intStack = new GenericStack<>();
4 intStack.push( 1 ); // 1 is autoboxed into new Integer(1)
5 intStack.push( 2 );
6 intStack.push( -2 );
7
8 System.out.print( "The max number is " + max(intStack));
9 }
10
GenericStack<Integer>
type
 
 
 
Search WWH ::




Custom Search