Java Reference
In-Depth Information
a ClassCastException caused by a cast inserted by the compiler that will point to a place in
my client code where, when I look at the source, there is no class cast.
There are other, more obscure places where you can also get into trouble using generics. For
example, there are tricks that can be used in object serialization (discussed in Chapter 9 ) that
require casting, since serialization entails converting a series of bits into an object. Most of
these problems come down to the lack of runtime support for generics, which makes generics
a compile-time system, coupled with the fact that Java is a dynamic environment in which a
lot happens at runtime.
When generics were first proposed, there were many who were upset with this mismatch. I
was one of them. This is not to say that the design is bad; indeed, given the constraint that
the virtual machine could not be changed, the design of generics is intellectually remarkable.
But because of the constraints on the design, the design does not fit naturally with the basic
nature of the language and environment. So although remarkable, it is not a perfect fit, and the
resulting system has some obscure holes.
All that said, after using generics for a couple of years, I think that they do make the language
better. While I'm not sure I would include them in the good parts of the language, they cer-
tainly get my vote for inclusion into the useful parts of the language. They are useful bits of
documentation, and do discover some errors at compile time that would have been revealed
only at runtime before generics were added. They are complicated to use in some of their more
obscure patterns. [ 24 ] But the simple uses are easy to understand and make your code better.
Advanced Topics
Before leaving our discussion of the collections, let's look at a couple of uses of those classes
that might not immediately spring to mind when we think about aggregating objects together.
As useful as the basic aggregations are, these others can save you even more time, and let you
avoid introducing even more bugs into your code.
Thus far, our statistics package has let us collect statistics and put Player objects together as
Team s. But we would like to be able to compare the statistics of the various players. There are
two tasks that we will need to do to get to a point where this is possible. The first is to asso-
ciate the various ways we have of gathering statistics, embodied in our notions of a Batter ,
Fielder , and Catcher , with our Player objects. The second is to come up with some way of
sorting those various categories into lists that will allow the comparison.
Search WWH ::

Custom Search