Java – how to return type the return type is also the upper and lower limits of method parameters
Let's assume we have the following code:
class A {} class B extends A {} class C extends B {} public static <T> T testMe(List<? super T> list1,List<? extends T> list2) { return null; } public static void main(String[] args) { List<B> listB = new ArrayList<>(); List<C> listC = new ArrayList<>(); // All three variants are possible: A a=testMe(listB,listC); B b=testMe(listB,listC); C c=testMe(listB,listC); }
The problem is about public static < T > t testme (list LIST1, list List2) If there are three classes, how does the compiler determine the T type: A, B, C,? When I analyze collections This problem occurs when copying
Solution
In all three cases, the compiler infers the type C of the type parameter t
Most specific type meets the constraint
For the first two statements,
A a = testMe(listB,listC); B b = testMe(listB,listC);
Both B and C match because list < b > matches list and list < C > match list and list < b > match list and list < C > match list The compiler selects the most specific type to match. C. you can compile with explicit type parameters to enable the compiler to resolve it to B:
A a = Super.<B>testMe(listB,listC); B b = Super.<B>testMe(listB,listC);
In the third line, only C matches, which is what the compiler chooses for t
C c = testMe(listB,listC);
This happens because the assigned variable is of type C, and B cannot be assigned to C