java - Java PECS 无法添加到使用者
问题描述
为什么我不能向消费者添加整数?
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
解决方案
简单的答案:因为在您的示例中与 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在这里阅读
推荐阅读
- bash - bash、awk 和/或 sed 清理具有特殊格式的字符串
- sql - 使用 ORACLE SQL 从不同行查询数据
- javascript - 更新 select2 组件的选项 - vue js
- c++ - LoadLibrary : 在发布模式下崩溃
- apache-zookeeper - zookeeper - Force Leader 选举
- matlab - MATLAB:根据列值过滤结构
- ruby-on-rails - 如何在活动记录的 jsonb 列中保存参数对象
- powerbi - Power BI 计算连续出现的次数
- php - 错误:使用 codeigniter 登录和注销时
- node.js - 如何在nodejs中加密和解密字符串/对象