Why can I not add an integer to the consumer?
import java.util.*;
public class Test
{
public static void main(String[] args)
{
List<Integer> integers = new ArrayList<>();
test(integers);
}
public static <T> void test(List<? super T> to)
{
to.add(32);
}
}
According to PECS (Producer extends, Consumer super), I use super, but this error occurs:
Test.java:13: error: no suitable method found for add(int)
to.add(32);
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
where T is a type-variable:
T extends Object declared in method <T>test(List<? super T>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: T from capture of ? super T
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
test
, what is known aboutT
? – SaviorT
will always be numeric type which accept 32 as its representation? If you would haveList<? super Integer> to
compiler would not have problem with allowing to add 32 to it. – Pshemo