Java Reference
In-Depth Information
12
13
// Stack<Double> assigned to Stack of raw types variable
Stack rawTypeStack2 = new Stack<Double>(5);
14
15
16
// Stack of raw types assigned to Stack<Integer> variable
Stack<Integer> integerStack = new Stack(10);
17
18
19
testPush( "rawTypeStack1" , rawTypeStack1, doubleElements);
20
testPop( "rawTypeStack1" , rawTypeStack1);
21
testPush( "rawTypeStack2" , rawTypeStack2, doubleElements);
22
testPop( "rawTypeStack2" , rawTypeStack2);
23
testPush( "integerStack" , integerStack, integerElements);
24
testPop( "integerStack" , integerStack);
25
}
26
27
// generic method pushes elements onto stack
28
public static <T> void testPush(String name, Stack<T> stack,
29
T[] elements)
30
{
31
System.out.printf( "%nPushing elements onto %s%n" , name);
32
33
// push elements onto Stack
34
for (T element : elements)
35
{
36
System.out.printf( "%s " , element);
37
stack.push(element); // push element onto stack
38
}
39
}
40
41
// generic method testPop pops elements from stack
42
public static <T> void testPop(String name, Stack<T> stack)
43
{
44
// pop elements from stack
45
try
46
{
47
System.out.printf( "%nPopping elements from %s%n" , name);
48
T popValue; // store element removed from stack
49
50
// remove elements from Stack
51
while ( true )
52
{
53
popValue = stack.pop(); // pop from stack
54
System.out.printf( "%s " , popValue);
55
}
56
} // end try
57
catch (EmptyStackException emptyStackException)
58
{
59
System.out.println();
60
emptyStackException.printStackTrace();
61
}
62
}
63
} // end class RawTypeTest
Fig. 20.11 | Raw-type test program. (Part 2 of 3.)
Search WWH ::




Custom Search