Consider the above code example.
Why the compiler complains about “incompatible types” in the for-each-loop and says:
B.java:10: incompatible types
found : java.lang.Object
required: java.lang.String
for (String k : a.m.keySet()) {
If I strip the type parameter all compiles fine.
public class A<T> {
Map<String,Field> m;
void foo() {
new B(this).foo();
}
}
class B {
A a;
B(A a) {
this.a = a;
}
void foo() {
for (String k : a.m.keySet()) {
}
}
}
No time to find the corresponding JLS part, but it’s simple: If you declare a class with a type parameter and then use it without it, the compiler removes all generic declarations of the class. I.e.
becomes
The fix is obvious: Instantiate A with a generic parameter or remove T.