Java Reference
In-Depth Information
(Figure 6-4 continued)
(b)
0
1
2
3
Array
3
topIndex
Top entry of stack
Stack
6.8
An outline of the class.
The array-based implementation of the stack has as data fields an array
of stack entries and an index to the top entry. The default constructor creates a stack with a
default capacity; another constructor lets the client choose the stack's capacity. Listing 6-2
outlines our class.
LISTING 6-2
An outline of an array-based implementation of the ADT stack
/**
A class of stacks whose entries are stored in an array.
@author Frank M. Carrano
*/
public class
ArrayStack<T>
implements
StackInterface<T>
{
private
T[] stack;
// array of stack entries
private int
topIndex;
// index of top entry
private static final int
DEFAULT_INITIAL_CAPACITY = 50;
public
ArrayStack()
{
this
(DEFAULT_INITIAL_CAPACITY);
}
// end default constructor
public
ArrayStack(
int
initialCapacity)
{
// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempStack = (T[])
new
Object[initialCapacity];
stack = tempStack;
topIndex = -1;
}
// end constructor
< Implementations of the stack operations go here. >
. . .
}
// end ArrayStack