Java Reference
In-Depth Information
L
ISTING
10.7
TestStackOfIntegers.java
1
public class
TestStackOfIntegers {
2
public static void
main(String[] args) {
3
4
5
StackOfIntegers stack =
new
StackOfIntegers();
create a stack
for
(
int
i =
0
; i <
10
; i++)
6
7
8
while
(!stack.empty())
9 System.out.print(
stack.push(i);
push to stack
stack.pop()
+
" "
);
pop from stack
10 }
11 }
9 8 7 6 5 4 3 2 1 0
How do you implement the
StackOfIntegers
class? The elements in the stack are stored in
an array named
elements
. When you create a stack, the array is also created. The no-arg
constructor creates an array with the default capacity of
16
. The variable
size
counts the
number of elements in the stack, and
size - 1
is the index of the element at the top of the
stack, as shown in Figure 10.12. For an empty stack,
size
is
0
.
elements[capacity
1]
.
.
.
elements[size
1]
top
capacity
.
.
.
size
elements[1]
elements[0]
bottom
F
IGURE
10.12
The
StackOfIntegers
class encapsulates the stack storage and provides
the operations for manipulating the stack.
The
StackOfIntegers
class is implemented in Listing 10.8. The methods
empty()
,
peek()
,
pop()
, and
getSize()
are easy to implement. To implement
push(int value)
, assign
value
to
elements[size]
if
size < capacity
(line 24). If the stack is full (i.e.,
size >=
capacity
), create a new array of twice the current capacity (line 19), copy the contents of the
current array to the new array (line 20), and assign the reference of the new array to the current
array in the stack (line 21). Now you can add the new value to the array (line 24).
L
ISTING
10.8
StackOfIntegers.java
1
public
class
StackOfIntegers
{
2
private int
[] elements;
3
private int
size;
4
public static final int
DEFAULT_CAPACITY =
16
;
max capacity 16
5
6
/** Construct a stack with the default capacity 16 */
7
public
StackOfIntegers()
{
8
this
(DEFAULT_CAPACITY);