为什么我不能向消费者添加一个整数?
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);
}
}根据PECS (Producer extends,Consumer super),我使用的是super,但出现了这个错误:
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发布于 2020-04-09 23:01:31
答案很简单:因为在您的示例中没有与int的T关系。
然而,它的工作方式如下:
public class Test
{
public static void main(String[] args)
{
List<Integer> integers = new ArrayList<>();
test(integers, 32);
}
public static <T> void test(List<? super T> to, T elem)
{
to.add(elem);
}
}也是这样的:
public class Test
{
public static void main(String[] args)
{
List<Integer> integers = new ArrayList<>();
test(integers);
}
public static void test(List<? super Integer> to)
{
to.add(32);
}
}原因是你需要“解释”编译器你的集合类型是如何与元素类型相关的。
PS有一个读here
https://stackoverflow.com/questions/61124009
复制相似问题