Java Reference
In-Depth Information
Example 7-5. ToyStack
public
public class
class
ToyStack
ToyStack
{
/** The maximum stack depth */
protected
protected
int
int
MAX_DEPTH
=
10
;
/** The current stack depth */
protected
protected
int
int
depth
=
0
;
/* The actual stack */
protected
protected
int
int
[]
stack
=
new
new
int
int
[
MAX_DEPTH
];
/** push - add an element onto the stack */
protected
protected
void
int
n
) {
stack
[
depth
++] =
n
;
void
push
(
int
}
/** pop - return and remove the top element */
protected
protected
int
int
pop
() {
return
return
stack
[--
depth
];
}
/** peek - return the top element but don't remove it */
protected
protected
int
int
peek
() {
return
return
stack
[
depth
-
1
];
}
}
If you are not familiar with the basic idea of a stack, you should work through the code here;
if you are familiar with it, you can skip ahead. While looking at it, of course, think about
what happens if
pop()
or
peek()
is called when
push()
has never been called, or if
push()
is called to stack more data than will fit.
A second version of this code,
ToyStack2
, has been changed to implement my
SimpleStack
interface and parameterized, so that we can use it with objects of any type. There is a tiny
performance hit here; the previous version dealt with primitive ints rather than objects.
However, the generality gain is probably more significant: we can use any kind of values in
this stack:
Example 7-6. ToyStack2
/** Toy Stack, converted to SimpleStack interface.
*/
public
public class
class
ToyStack2
ToyStack2
implements
implements
SimpleStack
<
Integer
> {
/** The maximum stack depth */
protected
protected
int
int
MAX_DEPTH
=
10
;
/** The current stack depth */