Java 泛型枚举子类型化接口(interface)

标签 java generics types enums

给定以下设置:

  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/

相关文章:

java - 为什么这个带有泛型返回的方法不能正确使用泛型类型?

matrix - 如何将任意大小的矩阵传递给 Rust 中的函数?

c# - .NET - 自定义类型可能吗?

Java 泛型 : compilation failure using captures

types - Julia 中的文字类型

Java比较列表的行与列表

java - Spring Boot Pojo 的 Pojo 验证不起作用

JAVA Apache POI : Getting a "We found a problem with some content in *.xlsx. Do you want us to try to recover it as much as we can" error

java - 为什么@Repeatable注解不能继承接口(interface)

java - 如何将嵌套的 Scala 集合转换为嵌套的 Java 集合