Java Reference
In-Depth Information
6.16
An outline of the class.
The class that implements the stack begins by declaring a vector as a data
field and allocating the vector in its constructors. Thus, we must provide an
import
statement prior
to the class definition. Listing 6-3 outlines our class.
LISTING 6-3
An outline of a vector-based implementation of the ADT stack
import
java.util.Vector;
/**
A class of stacks whose entries are stored in a vector.
@author Frank M. Carrano
*/
public class
VectorStack<T>
implements
StackInterface<T>
{
private
Vector<T> stack;
// last element is the top entry in stack
private static final int
DEFAULT_INITIAL_CAPACITY = 50;
public
VectorStack()
{
this
(DEFAULT_INITIAL_CAPACITY);
}
// end default constructor
public
VectorStack(
int
initialCapacity)
{
stack =
new
Vector<T>(initialCapacity);
// size doubles as needed
}
// end constructor
< Implementations of the stack operations go here. >
. . .
}
// end VectorStack
6.17
Adding to the top.
We use
Vector
's method
add
to add an entry to the end of the vector, that is, to
the top of the stack.
public void
push(T newEntry)
{
stack.add(newEntry);
}
// end push
6.18
Retrieving the top.
We retrieve the stack's top entry by using
Vector
's method
lastElement
.
public
T peek()
{
T top =
null
;
if
(!isEmpty())
top = stack.lastElement();
return
top;
}
// end peek