Java Reference
In-Depth Information
Pushing elements onto rawTypeStack1
1.1 2.2 3.3 4.4 5.5
Popping elements from rawTypeStack1
5.5 4.4 3.3 2.2 1.1
EmptyStackException: Stack is empty, cannot pop
at Stack.pop(Stack.java:32)
at RawTypeTest.testPop(RawTypeTest.java:53)
at RawTypeTest.main(RawTypeTest.java:20)
Pushing elements onto rawTypeStack2
1.1 2.2 3.3 4.4 5.5
Popping elements from rawTypeStack2
5.5 4.4 3.3 2.2 1.1
EmptyStackException: Stack is empty, cannot pop
at Stack.pop(Stack.java:32)
at RawTypeTest.testPop(RawTypeTest.java:53)
at RawTypeTest.main(RawTypeTest.java:22)
Pushing elements onto integerStack
1 2 3 4 5 6 7 8 9 10
Popping elements from integerStack
10 9 8 7 6 5 4 3 2 1
EmptyStackException: Stack is empty, cannot pop
at Stack.pop(Stack.java:32)
at RawTypeTest.testPop(RawTypeTest.java:53)
at RawTypeTest.main(RawTypeTest.java:24)
Fig. 20.11 | Raw-type test program. (Part 3 of 3.)
Compiler Warnings
Figure 20.12 shows the warning messages generated by the compiler when the file Raw-
TypeTest.java (Fig. 20.11) is compiled with the -Xlint:unchecked option, which pro-
vides more information about potentially unsafe operations in code that uses generics. The
first warning in Fig. 20.11 is generated for line 17, which assigned a raw-type Stack to a
Stack<Integer> variable—the compiler cannot ensure that all objects in the Stack will be
Integer objects. The next warning occurs at line 19. The compiler determines method
testPush 's type argument from the Double array passed as the third argument, because
the second method argument is a raw-type Stack variable. In this case, Double is the type
argument, so the compiler expects a Stack<Double> as the second argument. The warning
occurs because the compiler cannot ensure that a raw-type Stack contains only Double s.
The warning at line 21 occurs for the same reason, even though the actual Stack that
rawTypeStack2 references is a Stack<Double> . The compiler cannot guarantee that the
variable will always refer to the same Stack object, so it must use the variable's declared
type to perform all type checking. Lines 20 and 22 each generate warnings because method
testPop expects as an argument a Stack for which a type argument has been specified.
However, in each call to testPop , we pass a raw-type Stack variable. Thus, the compiler
indicates a warning because it cannot check the types used in the body of the method. In
general, you should avoid using raw types.
Search WWH ::




Custom Search