Java Reference
In-Depth Information
A stack in Java doesn't have a spring, but it does have all the facilities of a vector because the generic
Stack<>
type is derived from the
Vector<>
type. Of course, you know the
Vector<>
class implements the
List<>
interface so a
Stack<>
object is also a
List<>
.
The
Stack<T>
class adds five methods to those inherited from
Vector<T>
, two of which provide you
with the LIFO mechanism; the other three give you extra capabilities. These methods are:
•
T push(T obj)
: Pushes
obj
onto the top of the stack. It also returns the
obj
reference.
•
T pop()
: Pops the object off the top of the stack and returns it. This removes the reference from
the stack. If the stack contains no references when you call this method, an
EmptyStackExcep-
tion
is thrown.
•
T peek()
: Returns the object reference at the top of the stack without removing it. Like the previ-
ous method, this method can throw an
EmptyStackException
.
•
int search(Object obj)
: Returns a value that is the position of
obj
on the stack. The reference
at the top of the stack is at position 1, the next reference is at position 2, and so on. Note that this
is quite different from referencing elements in a
Vector<>
or an array, where indexes start at 0. If
the object isn't found on the stack, -1 is returned.
•
boolean empty()
: Returns
true
if the stack is empty and returns
false
otherwise.
The only constructor for a
Stack<>
object is the no-arg constructor. This calls the default constructor for
the base class,
Vector<>
, so you always get an initial capacity for 10 objects. Because it's basically a vector
a stack grows automatically in the same way.
One possible point of confusion is the relationship between the top of a
Stack<>
object and the elements
in the underlying
Vector<>
object. Intuitively, you might think that the top of the stack is going to corres-
pond to the first element in the vector, with index 0. If so, you would be totally
wrong
! The
push()
method
for a
Stack<>
object is analogous to
add()
for a
Vector<>
, which adds an object to the end of the vector.
Thus, the top of the stack corresponds to the end of the vector.
Let's try a
Stack<>
object out in an example so you get a feel for how the methods are used.