So strange! First look at the code:
public class A {} public class B extends A {} public class C extends A {} public class TestMain { public <T extends A> void test(T a, T b) {} public <T extends A> void test(List<T> a, List<T> b) {} public void test1(List<? extends A> a, List<? extends A> b) {} public static void main(String[] args) { new TestMain().test(new B(), new C()); new TestMain().test(new ArrayList<C>(), new ArrayList<C>()); new TestMain().test(new ArrayList<B>(), new ArrayList<C>()); new TestMain().test1(new ArrayList<B>(), new ArrayList<C>()); } }
In the statement new TestMain().test(new ArrayList<B>(), new ArrayList<C>()) a compilation error appears:
Associated mismatch: a general test of a method (T, T) of type TestMain is not applicable for arguments (ArrayList<B>, ArrayList<C>) . The inferred type ArrayList<? extends A> ArrayList<? extends A> not a valid replacement for the <T extends A> limited parameter
But:
new TestMain().test(new B(), new C()) --> compiled ok new TestMain().test(new ArrayList<C>(), new ArrayList<C>()) --> compiled ok new TestMain().test1(new ArrayList<B>(), new ArrayList<C>()) --> compiled ok
If we define a generic type before the method name, it seems that the type of the second generic List parameter should be the same as the first. But there are no restrictions if we define general parameters.
Is this a sign or a compilation error? Is there any documentation about this?
java collections generics compiler-errors
Geln yang
source share