Java Reference
In-Depth Information
Stacks
Stacks are a classic data structure used to model information accessed in a specific order.
The Stack class in Java is implemented as a last-in-first-out (LIFO) stack, which means
that the last item added to the stack is the first one to be removed. Figure 8.2 shows the
logical organization of a stack.
FIGURE 8.2
The organization of
a stack.
Position
from
top
To p
0
Element3
1
Element2
2
Element1
3
Bottom
Element0
You might wonder why the numbers of the elements don't match their positions from the
top of the stack. Keep in mind that elements are added to the top, so Element0 , which is
on the bottom, was the first element added to the stack. Likewise, Element3 , which is on
top, was the last element added. Also because Element3 is at the top of the stack, it will
be the first to be removed.
The Stack class defines only one constructor, which is a default constructor that creates
an empty stack. You use this constructor to create a stack like this:
Stack s = new Stack();
Stacks in Java are subclasses of Vector , so you can work with them as you would any
vector. They also contain methods specific to stack manipulation.
You can add new elements to a stack by using the push() method, which pushes an ele-
ment onto the top of the stack:
s.push(“One”);
s.push(“Two”);
s.push(“Three”);
s.push(“Four”);
s.push(“Five”);
s.push(“Six”);
Search WWH ::




Custom Search