img
Notice this line:
int v = (Integer) iOb.getob();
Because the return type of getob( ) is Object, the cast to Integer is necessary to enable that
value to be auto-unboxed and stored in v. If you remove the cast, the program will not compile.
With the generic version, this cast was implicit. In the non-generic version, the cast must be
explicit. This is not only an inconvenience, but also a potential source of error.
Now, consider the following sequence from near the end of the program:
// This compiles, but is conceptually wrong!
iOb = strOb;
v = (Integer) iOb.getob(); // run-time error!
Here, strOb is assigned to iOb. However, strOb refers to an object that contains a string, not
an integer. This assignment is syntactically valid because all NonGen references are the same,
and any NonGen reference can refer to any other NonGen object. However, the statement is
semantically wrong, as the next line shows. Here, the return type of getob( ) is cast to Integer,
and then an attempt is made to assign this value to v. The trouble is that iOb now refers to
an object that stores a String, not an Integer. Unfortunately, without the use of generics, the
Java compiler has no way to know this. Instead, a run-time exception occurs when the cast
to Integer is attempted. As you know, it is extremely bad to have run-time exceptions occur
in your code!
The preceding sequence can't occur when generics are used. If this sequence were
attempted in the generic version of the program, the compiler would catch it and report an
error, thus preventing a serious bug that results in a run-time exception. The ability to create
type-safe code in which type-mismatch errors are caught at compile time is a key advantage
of generics. Although using Object references to create "generic" code has always been
possible, that code was not type safe, and its misuse could result in run-time exceptions.
Generics prevent this from occurring. In essence, through generics, what were once
run-time errors have become compile-time errors. This is a major advantage.
A Generic Class with Two Type Parameters
You can declare more than one type parameter in a generic type. To specify two or more
type parameters, simply use a comma-separated list. For example, the following TwoGen
class is a variation of the Gen class that has two type parameters:
// A simple generic class with two type
// parameters: T and V.
class TwoGen<T, V> {
T ob1;
V ob2;
// Pass the constructor a reference to
// an object of type T and an object of type V.
TwoGen(T o1, V o2) {
ob1 = o1;
ob2 = o2;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home