Java Reference
In-Depth Information
We introduced the concept of a
stack
in Section 6.6 when we discussed the method-call
stack. In Chapter 21, Custom Generic Data Structures, we'll learn how to build data struc-
tures, including
linked lists
,
stacks
,
queues
and
trees
. In a world of software reuse, rather than
building data structures as we need them, we can often take advantage of existing data struc-
tures. In this section, we investigate class
Stack
in the Java utilities package (
java.util
).
Class
Stack
extends class
Vector
to implement a stack data structure. Figure 16.14
1
// Fig. 16.14: StackTest.java
2
// Stack class of package java.util.
3
4
5
6
import
java.util.Stack;
import
java.util.EmptyStackException;
public class
StackTest
7
{
8
public static void
main(String[] args)
9
{
10
Stack<Number> stack =
new
Stack<>();
// create a Stack
11
12
// use push method
13
stack.push(
12L
);
// push long value 12L
14
System.out.println(
"Pushed 12L"
);
15
printStack(stack);
16
stack.push(
34567
);
// push int value 34567
17
System.out.println(
"Pushed 34567"
);
18
printStack(stack);
19
stack.push(
1.0F
);
// push float value 1.0F
20
System.out.println(
"Pushed 1.0F"
);
21
printStack(stack);
22
stack.push(
1234.5678
);
// push double value 1234.5678
23
System.out.println(
"Pushed 1234.5678 "
);
24
printStack(stack);
25
26
// remove items from stack
27
try
28
{
29
Number removedObject =
null
;
30
31
// pop elements from stack
32
while
(
true
)
33
{
34
removedObject = stack.pop();
// use pop method
35
System.out.printf(
"Popped %s%n"
, removedObject);
36
printStack(stack);
37
}
38
}
39
catch
(EmptyStackException emptyStackException)
40
{
Fig. 16.14
|
Stack
class of package
java.util
. (Part 1 of 2.)