gpt4 book ai didi

java - 为什么使用泛型类型进行数组实例化在 Java 中不起作用?

转载 作者:行者123 更新时间:2023-11-30 03:51:58 25 4
gpt4 key购买 nike

public interface Foo<E> {

public void blah(E e);

}

public class MyClass<E> {

private final Foo<E>[] fooArray = new Foo<E>[8]; // does not compile!

// (...)

}

解决泛型限制的正确方法是什么?

或者也许这不是一个限制,我错过了一些东西?

最佳答案

make-it-compile 方式将使用泛型声明变量,但使用原始类型初始化数组(而不是元素):

//add @SuppressWarnings("unchecked") to avoid warnings
Foo<String>[] arrayOfFoo = new Foo[8];
arrayOfFoo[0] = new ClassThatImplementsFoo<String>();
//line below gives a compile error since the array declaration is for Foo<String>
//and won't allow Foo<AnotherClass>
arrayOfFoo[1] = new ClassThatImplementsFoo<Integer>();

更好、更安全的方法是使用 List 而不是普通数组:

List<Foo<String>> fooList = new ArrayList<Foo<String>>();
fooList.add(new ClassThatImplementsFoo<String>());
<小时/>

在您的代码中,您应该这样做:

public class MyClass<E> {
private final Foo<E>[] fooArray = new Foo[8];
// (...)
}

关于java - 为什么使用泛型类型进行数组实例化在 Java 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24208531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com