Java Reference
In-Depth Information
System.out.println("\t" + i.getName());
Best of all, we have eliminated all of the code that we had to check to make sure that the types
were correct in our collection. Because we were able to specify a type parameter on the col-
lections that we used, we can be sure that all that was put into the collection, and all that will
come out, are going to be objects of the right type. There are no casts in our code that could
cause a runtime exception to be thrown. So there is no way that this code can go wrong, at
least with respect to the types of the objects.
Well, mostly. In fact, the addition of generics and the parameterization of the collections do
not eliminate the possibility of having the wrong type of object in such a collection. To un-
derstand why requires that we look a little more carefully at how generics were added to the
The generics system was designed at a time when there was a prohibition about even thinking
about making changes to either the Java virtual machine or the bytecodes understood by that
machine. This was in keeping with a number of edicts at the time, but it was mostly a way of
ensuring that Java programs written on early versions of the platform ran on later versions of
the virtual machine. It is actually sort of amazing that the JVM itself has changed so little over
the years. Either through luck or skill, most of the changes have occurred in the libraries, with
a smaller set of changes occurring in the language and very little change occurring in the VM
But the inability to change the VM or bytecodes meant that parameterized types could occur
only in the source code. The type system of the runtime hasn't changed, and doesn't include
generics or parameterized types. What we see in our code as a Set<Player> is seen in the
bytecodes as simply a Set of objects.
In many ways, the fact that the designers of the generics system could do much of anything
without involving the runtime is a testament to their skills. The resulting system [ 23 ] uses lots
of tricks in the compiler to make sure that the type safety is guaranteed, and has the compiler
insert the casts that are needed to change the runtime objects that come from parameterized
collections into the correct type.
This has two implications. First, the casting of objects from one type to another is still in the
code, even though it is hidden from the programmer. Using generics just means that the com-
piler will insert the casts into your code rather than you having to write those casts. For those
who feel that the whole point of generics is to get away from such casts (because, for some
Search WWH ::

Custom Search