Java Reference
In-Depth Information
Stack
(Fig. 20.7), no upper bound is specified, so the default upper bound,
Object
, is
used. The scope of a generic class's type parameter is the entire class. However, type
parameters
cannot
be used in a class's
static
variable declarations.
1
// Fig. 20.8: EmptyStackException.java
2
// EmptyStackException class declaration.
3
public
class
EmptyStackException
extends
RuntimeException
4
{
5
// no-argument constructor
6
public
EmptyStackException()
7
{
8
this
(
"Stack is empty")
;
9
}
10
11
// one-argument constructor
12
public
EmptyStackException(String message)
13
{
14
super
(message);
15
}
16
}
// end class EmptyStackException
Fig. 20.8
|
EmptyStackException
class declaration.
Testing the Generic
Stack
Class of Fig. 20.7
Now, let's consider the application (Fig. 20.9) that uses the
Stack
generic class (Fig. 20.7).
Lines 12-13 in Fig. 20.9 create and initialize variables of type
Stack<Double>
(pro-
nounced “
Stack
of
Double
”) and
Stack<Integer>
(pronounced “
Stack
of
Integer
”). The
types
Double
and
Integer
are known as the
Stack
's
type arguments
. The compiler uses
them to replace the type parameters so that it can perform type checking and insert cast
operations as necessary. We'll discuss the cast operations in more detail shortly. Lines 12-
13 instantiate
doubleStack
with a capacity of
5
and
integerStack
with a capacity of 10
(the default). Lines 16-17 and 20-21 call methods
testPushDouble
(lines 25-36),
testPopDouble
(lines 39-59),
testPushInteger
(lines 62-73) and
testPopInteger
(lines 76-96), respectively, to demonstrate the two
Stack
s in this example.
1
// Fig. 20.9: StackTest.java
2
// Stack generic class test program.
3
4
public
class
StackTest
5
{
6
public static void
main(String[] args)
7
{
8
double
[] doubleElements = {
1.1
,
2.2
,
3.3
,
4.4
,
5.5};
9
int
[] integerElements = {
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
};
10
11
// Create a Stack<Double> and a Stack<Integer>
Stack<Double> doubleStack =
new
Stack<>(
5
);
Stack<Integer> integerStack =
new
Stack<>();
12
13
14
Fig. 20.9
|
Stack
generic class test program. (Part 1 of 3.)