Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Do generics add type safety to the language?

843793Apr 22 2003 — edited May 2 2003
I'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

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on May 30 2003
Added on Apr 22 2003
13 comments
143 views