Do generics add type safety to the language?
843793Apr 22 2003 — edited May 2 2003I'm probably missing something, but I do not quite understand why generics are supposed to add type safety to the language.
Consider the following example:
public class Tuple<Elem> {
private Elem p1, p2;
...
public <T extends Tuple> Tuple(T other) {
try {
this.p1 = (Elem) other.p1;
}
catch (ClassClastException e) {
this.p1 = null;
}
... same for p2 ...
}
}
I am trying to cast a variable of type T to a variable of type Elem, where both T and Elem are type parameters. This cast never fails. In fact, the following compiles and runs although one would hope that it would fail:
Tuple<String> pairOfAliens =
new Tuple<String>("Dick","Doof");
Tuple<Exception> pairOfExceptions =
new Tuple<Exception>(pairOfAliens);
The demonstrated behavior is correct, because the type parameters are mapped to Object references. But what do generics buy me in that case? I don't see that generics add much to the language in terms of type safety, except in the simplest of all conceivable cases (like the proposed generic collections).
Angelika