Java Reference
In-Depth Information
1
// Fig. 20.10: StackTest2.java
2
// Passing generic Stack objects to generic methods.
3
public class StackTest2
4
{
5
public static void main(String[] args)
6
{
7
Double
Integer
[] doubleElements = { 1.1 , 2.2 , 3.3 , 4.4 , 5.5 };
8
[] integerElements = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
9
10
// Create a Stack<Double> and a Stack<Integer>
11
Stack<Double> doubleStack = new Stack<>(5);
12
Stack<Integer> integerStack = new Stack<>();
13
14
// push elements of doubleElements onto doubleStack
testPush( "doubleStack" , doubleStack, doubleElements);
testPop( "doubleStack" , doubleStack); // pop from doubleStack
15
16
17
18
// push elements of integerElements onto integerStack
testPush( "integerStack" , integerStack, integerElements);
testPop( "integerStack" , integerStack); // pop from integerStack
19
20
21
}
22
23
// generic method testPush pushes elements onto a Stack
24
public static <T> void testPush(String name , Stack<T> stack,
T[] elements)
25
26
{
27
System.out.printf( "%nPushing elements onto %s%n" , name);
28
29
// push elements onto Stack
30
for (
T element : elements
)
31
{
32
System.out.printf( "%s " , element);
33
stack.push(element); // push element onto stack
34
}
35
}
36
37
// generic method testPop pops elements from a Stack
38
public static <T> void testPop(String name, Stack<T> stack)
39
{
40
// pop elements from stack
41
try
42
{
43
System.out.printf( "%nPopping elements from %s%n" , name);
44
T popValue; // store element removed from stack
45
46
// remove all elements from Stack
47
while ( true )
48
{
49
popValue = stack.pop();
50
System.out.printf( "%s " , popValue);
51
}
52
}
Fig. 20.10 | Passing generic Stack objects to generic methods. (Part 1 of 2.)
Search WWH ::




Custom Search