Java Reference
In-Depth Information
41
emptyStackException.printStackTrace();
42
}
43
}
44
45
// display Stack contents
46
private static void
printStack(Stack<Number> stack)
47
{
48
if
(
stack.isEmpty()
)
49
System.out.printf(
"stack is empty%n%n"
);
// the stack is empty
50
else
// stack is not empty
51
System.out.printf(
"stack contains: %s (top)%n"
, stack);
52
}
53
}
// end class StackTest
Pushed 12L
stack contains: [12] (top)
Pushed 34567
stack contains: [12, 34567] (top)
Pushed 1.0F
stack contains: [12, 34567, 1.0] (top)
Pushed 1234.5678
stack contains: [12, 34567, 1.0, 1234.5678] (top)
Popped 1234.5678
stack contains: [12, 34567, 1.0] (top)
Popped 1.0
stack contains: [12, 34567] (top)
Popped 34567
stack contains: [12] (top)
Popped 12
stack is empty
java.util.EmptyStackException
at java.util.Stack.peek(Unknown Source)
at java.util.Stack.pop(Unknown Source)
at StackTest.main(StackTest.java:34)
Fig. 16.14
|
Stack
class of package
java.util
. (Part 2 of 2.)
Error-Prevention Tip 16.1
Because
Stack
extends
Vector
, all
public
Vector
methods can be called on
Stack
ob-
jects, even if the methods do not represent conventional stack operations. For example,
Vector
method
add
can be used to insert an element anywhere in a stack—an operation
that could “corrupt” the stack. When manipulating a
Stack
, only methods
push
and
pop
should be used to add elements to and remove elements from the
Stack
, respectively. In
Section 21.5, we create a
Stack
class using composition so that the
Stack
provides in its
public
interface only the capabilities that should be allowed by a
Stack
.
Line 10 creates an empty
Stack
of
Number
s. Class
Number
(in package
java.lang
) is
the superclass of the type-wrapper classes for the primitive numeric types (e.g.,
Integer
,
Double
). By creating a
Stack
of
Number
s, objects of any class that extends
Number
can be
pushed onto the
Stack
. Lines 13, 16, 19 and 22 each call
Stack
method
push
to add a
Number
object to the
top
of the stack. Note the literals
12L
(line 13) and
1.0F
(line 19).
Any integer literal that has the
suffix
L
is a
long
value. An integer literal without a suffix