Java Reference
In-Depth Information
The “<>” is called the “diamond operator.” Prior to Java 7, the compiler was not smart
enough to apply the type parameter (
BankAccount
) from the declaration to the definition;
you had to repeat the (redundant) statement of the type:
MyStack
<
BankAccount
>
theAccounts
=
new
new
MyStack
<
BankAccount
>( );
Note that if you do not provide a specific type, this class defaults to the most general behavi-
or (i.e., type
T
is treated as
java.lang.Object
). So this little collection, like the real ones in
java.util
, will behave as they did in the days before Generic Collections—accepting input
arguments of any type, returning
java.lang.Object
from getter methods, and requiring
downcasting—as their default, backward-compatible behavior.
Example 7-3
shows a pro-
gram that creates two instances of
MyStack
, one specialized for
String
s and one left gener-
al. The general one, called
ms2
, is loaded up with the same two
String
objects as
ms1
but
also includes a
Date
object. The printing code is now “broken,” because it will throw a
ClassCastException
: a
Date
is not a
String
. I handle this case specially for pedantic pur-
poses: it is illustrative of the kinds of errors you can get into when using nonparameterized
container classes.
Example 7-3. MyStackDemo.java
public
public class
class
MyStackDemo
MyStackDemo
{
public
public static
void
main
(
String
[]
args
) {
MyStack
<
String
>
ms1
=
new
static
void
new
MyStack
<>();
ms1
.
push
(
"billg"
);
ms1
.
push
(
"scottm"
);
while
while
(
ms1
.
hasNext
()) {
String name
=
ms1
.
pop
();
System
.
out
.
println
(
name
);
}
// Old way of using Collections: not type safe.
// DO NOT GENERICIZE THIS
MyStack ms2
=
new
new
MyStack
();
ms2
.
push
(
"billg"
);
// EXPECT WARNING
ms2
.
push
(
"scottm"
);
// EXPECT WARNING
ms2
.
push
(
new
new
java
.
util
.
Date
());
// EXPECT WARNING
// Show that it is broken
try
try
{
String bad
= (
String
)
ms2
.
pop
();
System
.
err
.
println
(
"Didn't get expected exception, popped "
+
bad
);