给定以下设置:
public class TestType {
public static void main(String[] args) {
List<Constants> list = new ArrayList<>();
accept(list); //Does not compile
}
static void accept(Iterable<MyInterface> values) {
for (MyInterface value : values) {
value.doStuff();
}
}
}
interface MyInterface<T> {
T doStuff();
}
enum Constants implements MyInterface<Integer> {
ONE, TWO, THREE;
@Override
public Integer doStuff() {
return ordinal();
}
}
为什么编译器不接受列表作为 accept() 的参数?
List
延伸Iterable
通过Collection
所以这不是问题。
另一方面,编译器告诉我
incompatible types: java.util.List<enums.Constants> cannot be converted to java.lang.Iterable<enums.MyInterface>
但是常量是一个 MyInterface...不是吗?
最佳答案
问题在于泛型的工作方式。具体来说,泛型是非具体化的……这意味着编译器不会看到 Iterable<enum.Constants>
。作为Iterable<enum.MyInterface>
即使 Constants 是 MyInterface 的子类。
但是,有一种方法可以绕过它:Generic wildcards .
如果你改变static void accept(Iterable<MyInterface> values)
至 static void accept(Iterable<? extends MyInterface> values)
,它应该有效。
关于Java 泛型枚举子类型化接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35364707/