Look, we've got come code:
public class Test2 {
public static void main(String... args) {
ArrayList<Exception> a = new ArrayListFactory().create(new RuntimeException());
ArrayList<Exception> b = new ArrayListFactory().create("Z");
}
}
class ArrayListFactory {
public <T> ArrayList<T> create(T example) {
return new ArrayList<T>(10);
}
}
and an compilation error on second statement:
Error:(15, 63) java: incompatible types: inference variable T has incompatible bounds
equality constraints: java.lang.Exception
lower bounds: java.lang.String
- In fact, the first statement assigns to
ArrayList<Exception>
anotherArrayList<RuntimeException>
, doesnt it clash with java rules? - The second statement infers
Exception
type argument forcreate
. Does it check that method's return type matches it's argument type as it's defined in ArrayListFactory class? It seems that this method call shall be resolved dynamically, why is compiler sure that it's processing the correct method?