Java Reference
In-Depth Information
reason, those casts are evil), this is the moral equivalent of purchasing indulgences. Someone
else (the compiler) sins so that you don't have to. It hardly seems right.
I'll admit that this objection to generics doesn't really bother me, for the simple reason that
I don't think type casting in a language like Java is an indication that your code is somehow
faulty. I think this view is a holdover from the attitude that developed in languages like C,
where casting did show a weakness in the type system of the language. Of course, since C
didn't really have a type system, it isn't surprising that there were weaknesses to it. But I di-
The other implication, which is more serious, is that type safety for parameterized types can
only be ensured over a compilation unit. That means that if you are using code that was com-
piled elsewhere, you need to trust that whoever it was that wrote that code (even if it was
you some time earlier) made sure that all of the uses of parameterized types were safe in their
code. If that code was not completely type-safe, you may run into trouble using the code, and
you won't know it until the problem happens.
To see an example, let's return to our TeamImpl class. We will leave it exactly the way it
is, except that we will change the internal representation of the players collection from a
HashSet<Player> to a simple HashSet . A collection without a type parameter is perfectly
legal, left in to make sure that programs written before generics were added still work. The
code will still compile, although I will get a warning from the compiler like: uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
But this is a warning, easy to ignore (and, at times, easy to miss among the other warnings
generated by the compiler). I should make the changes to my code that would eliminate the
warning, but there are all kinds of things that I should do that I don't get around to doing.
Even with the warning, the compiler will generate a class file, and the program will run just
fine. Until it doesn't.
If this isn't repaired, then I'm back to the situation where something other than a Player ob-
ject might make it into the collection of players. If there is some other way to access the local
collection, or some method that also is missing a type parameter, then most anything could be
placed in the HashSet . And, as I write the client code that uses the TeamImpl class (probably
through the Team interface), I will never know. Unless I compile the TeamImpl class myself
along with any code that I write that uses that class (and I might not even have the code), I will
never get the warning. But my client code may fail when running. Even worse, it will fail with
Search WWH ::

Custom Search