Java Reference
In-Depth Information
4
5
for
(
int
i =
0
; i <
10
; i++)
6
stack.push(i);
push to stack
7
8
while
(!stack.empty())
9 System.out.print(stack.pop() +
" "
);
10 }
11 }
pop from stack
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.13. For an empty stack,
size
is
0
.
elements[capacity
1]
.
.
.
elements[size
1]
top
capacity
.
.
.
size
elements[1]
elements[0]
bottom
F
IGURE
10.13
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 con-
tents 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);
9 }
10
11
/** Construct a stack with the specified maximum capacity */
12
public
StackOfIntegers(
int
capacity) {
13 elements =
new int
[capacity];
14 }
15
Search WWH ::
Custom Search