java - 如何在 Java 中使用数组进行类型泛型?

标签 java generics types polymorphism

在 java 中,我想创建一个函数,它接受任何类型内容的列表,然后返回相同类型的数组。我到此为止

public static <T>[] listToArray(List<T> items) {
    <T>[] names = new <T>[items.size()];
    for(int i=0; i<items.size(); i+=1) {
        names[i] = items.get(i);
    }
    return names;
}

但这有很多语法错误...

有人知道怎么做吗?

谢谢

最佳答案

来自 Bloch 的 Effective Java,第 25 项:

...arrays and generics have very different type rules. Arrays are covariant and reified; generics are invariant and erased. As a consequence, arrays provide runtime type safety but not compile-time type safety and vice versa for generics. Generally speaking, arrays and generics don’t mix well. If you find yourself mixing them and getting compile-time errors or warnings, your first impulse should be to replace the arrays with lists.

解释:

数组是协变的意味着如果 Dog 类扩展 Animal 类,那么您可以:

Animal[] animals = new Animal[5];
animals[0] = new Dog();

这同样不适用于泛型,因为泛型是不变的:

List<Animal> animals = new LinkedList<Animal>();
animals.add(new Dog()); // compilation error!!!

数组被具体化意味着关于数组类型的所有信息在运行时和编译时都是可用的。同样,泛型被删除,这意味着类型信息仅在编译时存在。

关于java - 如何在 Java 中使用数组进行类型泛型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24879051/

相关文章:

C++ 128/256 位固定大小整数类型

java - 有什么方法可以使用带有两对不同分隔符的正则表达式吗?

java - 在 Prepared Statement 中设置 boolean 值的最佳实践

java - 在 Java 中返回反向泛型列表类型

c# - 我可以在 List<T> 中搜索特定值吗?

c# - LINQ to Objects 缓慢。现在我完全糊涂了

java - 返回中的不兼容类型错误给我错误?

php - PHP 数组可以容纳不同类型的项目吗?

java - 圆的 3D 旋转使边缘交叉两点

java - 我想在 lotus Notes 6.5 中使用 java 1.6。有没有办法做到这一点..? –