Java Reference
In-Depth Information
In this case, the
objectStack
has a
raw type
—the compiler implicitly uses type
Object
throughout the generic class for each type argument. Thus the preceding statement creates a
Stack
that can store objects of
any
type. This is important for
backward compatibility
with
prior Java versions. For example, the data structures of the Java Collections Framework
(Chapter 16) all stored references to
Object
s, but are now implemented as generic types.
A raw-type
Stack
variable can be assigned a
Stack
that specifies a type argument, such
as a
Stack<Double>
object, as follows:
Stack rawTypeStack2 =
new
Stack<Double>(
5
);
because type
Double
is a subclass of
Object
. This assignment is allowed because the ele-
ments in a
Stack<Double>
(i.e.,
Double
objects) are certainly objects—class
Double
is an
indirect subclass of
Object
.
Similarly, a
Stack
variable that specifies a type argument in its declaration can be
assigned a raw-type
Stack
object, as in:
Stack<Integer> integerStack =
new
Stack(
10
);
Although this assignment is permitted, it's
unsafe
, because a
Stack
of raw type might store
types other than
Integer
. In this case, the compiler issues a warning message which indi-
cates the unsafe assignment.
Using Raw Types with Generic Class Stack
The test program of Fig. 20.11 uses the notion of raw type. Line 11 instantiates generic class
Stack
with raw type, which indicates that
rawTypeStack1
can hold objects of any type. Line
14 assigns a
Stack
<
Double
> to variable
rawTypeStack2
, which is declared as a
Stack
of raw
type. Line 17 assigns a
Stack
of raw type to
Stack
<
Integer
> variable, which is legal but
causes the compiler to issue a warning message (Fig. 20.12) indicating a
potentially unsafe as-
signment
—again, this occurs because a
Stack
of raw type might store types other than
Inte-
ger
. Also, the calls to generic methods
testPush
and
testPop
in lines 19-22 result in
compiler warning messages (Fig. 20.12). These occur because
rawTypeStack1
and
rawTypeStack2
are declared as
Stack
s of raw type, but methods
testPush
and
testPop
each
expect a second argument that is a
Stack
with a specific type argument. The warnings indi-
cate that the compiler cannot guarantee the types manipulated by the stacks to be the correct
types, since we did not supply a variable declared with a type argument. Methods
testPush
(Fig. 20.11, lines 28-39) and
testPop
(lines 42-62) are the same as in Fig. 20.10.
1
// Fig. 20.11: RawTypeTest.java
2
// Raw type test program.
3
public class
RawTypeTest
4
{
5
public static void
main(String[] args)
6
{
7
Double[] doubleElements = {
1.1
,
2.2
,
3.3
,
4.4
,
5.5
};
8
Integer[] integerElements = {
1
,
2
,
3
,
4
,
5
,
6
,
7
,
8
,
9
,
10
};
9
10
// Stack of raw types assigned to Stack of raw types variable
Stack rawTypeStack1 =
new
Stack(5);
11
Fig. 20.11
|
Raw-type test program. (Part 1 of 3.)