Re:Java Generics FAQs
by tel on Thursday April 16, 2015 @09:21PM
(#9391775)
I'm assuming it's because the T variable isn't generalized over within the definition of Foo, so you can't use (test) at arbitrary types until Foo is closed?
[ Parent
| on HN ]
Re:Java Generics FAQs
by salmonellaeater on Thursday April 16, 2015 @10:21PM
(#9391948)
In concrete terms, imagine Foo looks like this:
private T value;
void test(Foo<T> f) {
f.value = this.value;
}
You could then assign anything to a member that should only hold a String.This is the same reason why arrays should not be covariant (even though they are in Java). This compiles:
Object[] arr = new Integer[2]; // This should be a compile error, but the language spec allows it
arr[0] = "abc"; // This blows up with an ArrayStoreException at runtimeYour example presents zero unsafety for the usage presented by eridal. The only reason it's considered unsafe is because the compiler isn't sophisticated enough to compare captures of wildcards, and in this case, might not be sophisticated enough to know that `f` isn't being reassigned.