Java Reference
In-Depth Information
return topIndex < 0;
} // end isEmpty
The method clear could simply set topIndex to - 1, because the stack methods would behave
correctly as though the stack were empty. However, the objects that were in the stack would remain
allocated. Just as pop sets stack[topIndex] to null , clear should set to null each array location
that was used for the stack. Alternatively, clear could call pop repeatedly until the stack is empty.
We leave the implementation of clear as an exercise.
Question 5 If stack is an array that contains the entries in a stack, what is a disadvantage
of maintaining the top entry of the stack in stack[0] ?
Question 6 If you use the locations at the end of an array stack for a stack's entries before
you use the array's first locations, should the stack's top entry or its bottom entry be in
stack[stack.length - 1] ? Why?
Question 7 Write an implementation of clear that sets to null each array location that
was used for the stack.
Question 8 Write an implementation of clear that repeatedly calls pop until the stack is empty.
A Vector-Based Implementation
6.13
One way to let a stack grow as needed is to store its entries in an array that you resize, as we did in
the implementation of ArrayStack . Another way is to use a vector instead of an array. A vector is
an object that behaves like a high-level array. A vector's entries are indexed beginning with 0, just
like an array's entries. But unlike an array, a vector has methods to set or access its entries. You can
create a vector of a given size, and it will grow in size as needed. The details of this process are hid-
den from the client.
If we store a stack's entries in a vector, we can use the vector's methods to manipulate the stack's
entries. Figure 6-6 shows a client interacting with a stack by using the methods in StackInterface .
The implementations of these methods in turn interact with the vector's methods to produce the
desired effects on the stack.
A vector is an instance of the standard class Vector , which we describe next.
FIGURE 6-6
A client using the methods given in StackInterface ; these
methods interact with a vector's methods to perform stack
operations
StackInterface
Client
A vector
Implementation of a stack
 
 
Search WWH ::




Custom Search