首页 > 解决方案 > 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

标签: java

解决方案


简单的答案:因为在您的示例中与 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在这里阅读


推荐阅读