Java泛型、通配符、集合: compilation error

标签 java generics collections bounded-wildcard

给定以下类(class):

import java.util.ArrayList;
import java.util.Collection;

public class Main {

    private static class A {
    }

    private static class B<T> {
        private void thenReturn(T value) {
        }
    }

    private static <T> B<T> when(T methodCall) {
        return new B<T>();
    }

    private static Collection<? extends A> method() {
        return new ArrayList<>();
    }

    public static void main(String[] args) {
        Collection<? extends A> result = new ArrayList<>();
        // Does not compile.
        when(method()).thenReturn(result);
    }

}

我收到编译错误 The method thenReturn(Collection<capture#1-of ? extends Main.A>) in the type Main.B<Collection<capture#1-of ? extends Main.A>> is not applicable for the arguments (Collection<capture#3-of ? extends Main.A>)

我需要在 main 方法中更改哪些内容才能编译?有没有更好的解决方案

    public static void main(String[] args) {
        Collection result = new ArrayList<>();
        when(method()).thenReturn(result);
    }

最佳答案

这可以解决这个问题 - 看起来捕获规则对于长表达式来说有点紧张。

    Collection<? extends A> result = new ArrayList<>();
    B<Collection<? extends A>> when = when(method());
    when.thenReturn(result);

关于Java泛型、通配符、集合: compilation error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35796820/

相关文章:

java - Java 应用程序的多核 CPU 利用率

java - 如何通过 Android Facebook API 使用基于光标的分页

c# - 为什么 NotifyCollectionChangedEventArgs 有 NewItems 和 OldItems 作为复数?

c# - 不能隐式转换类型 - 泛型

java - 如何在java中打印嵌套在数组中的对象

c# - 展平 IEnumerable<IEnumerable<>>;理解泛型

java - Hash Map 值是如何存储的(以防值重复)?

java - 我们可以创建具有动态键和动态值的 HashMap 吗?

algorithm - 我认为 "NlogN"是 "N"乘以 "logN",但为什么它被描述为 "double PLUS an amount proportional to N"

java - 小部件 Onclick 不起作用