Java Reference
In-Depth Information
Stack Storage
A stack is a storage mechanism that works on a last-in first-out basis, often abbreviated to LIFO. Don't
confuse this with FIFO, which is first-in first-out, or FIFI, which is a name for a poodle. The operation
of a stack is analogous to the plate stack you see in some self-service restaurants. The stack of plates is
supported by a spring that allows the stack of plates to sink into a hole in the countertop so that only the
top plate is accessible. The plates come out in the reverse order to the way they went in, so the cold
plates are at the bottom, and the hot plates fresh from the dishwasher are at the top.
Objects can only
be added to the
top of a stack
Only the top
object in a stack
is accessible
To remove this
element you must
remove the top
three first
A Stack
A stack in Java doesn't have a spring, but it does have all the facilities of a Vector object because the
class Stack is derived from the class Vector . Of course, since we know the Vector class implements
the List interface, a Stack object is also a List .
The Stack class adds five methods to those inherited from Vector , two of which provide you with the
LIFO mechanism, and the other three give you extra capabilities. These methods are:
Method
Description
push
(Object anObject)
Pushes a reference to the object passed as an argument to the
method onto the top of the stack.
pop()
Pops the object reference off the top of the stack and returns it as
type Object . This removes the reference from the stack. If the
stack contains no references when you call this method the
EmptyStackException will be thrown.
peek()
This method allows you to take a look at the object reference at
the top of the stack without popping it off the stack. It returns the
reference from the top of the stack as type Object without
removing it. Like the previous method, this method can throw an
EmptyStackException .
Table continued on following page
Search WWH ::




Custom Search