java - 在 Java 中创建一个数组来存储泛型类型

标签 java generics

假设我必须创建一个数组来存储 ArrayList 的整数,并且数组大小为 10。

下面的代码可以做到:

ArrayList<Integer>[] pl2 = new ArrayList[10]; 

问题 1:

我认为更合适的代码是

ArrayList<Integer>[] pl2 = new ArrayList<Integer>[10];    

为什么这不起作用?

问题 2:

以下都编译

  1. ArrayList<Integer>[] pl2 = new ArrayList[10];
  2. ArrayList[] pl3 = new ArrayList[10];

pl2 的引用声明有什么区别?和 pl3担心吗?

最佳答案

泛型信息只在编译时很重要,它告诉编译器可以将哪种类型放入数组中,在运行时,所有泛型信息都将被删除,所以重要的是如何声明泛型类型。

引自 Think in Java:

it’s not precisely correct to say that you cannot create arrays of generic types. True, the compiler won’t let you instantiate an array of a generic type. However, it will let you create a reference to such an array. For example:

List<String>[] ls; 

This passes through the compiler without complaint. And although you cannot create an actual array object that holds generics, you can create an array of the non-generified type and cast it:

//: arrays/ArrayOfGenerics.java 
// It is possible to create arrays of generics. 
import java.util.*; 

public class ArrayOfGenerics { 
    @SuppressWarnings("unchecked") 
    public static void main(String[] args) { 
        List<String>[] ls; 
        List[] la = new List[10]; 
        ls = (List<String>[])la; // "Unchecked" warning 
        ls[0] = new ArrayList<String>(); 
        // Compile-time checking produces an error: 
        //! ls[1] = new ArrayList<Integer>(); 

        // The problem: List<String> is a subtype of Object 
        Object[] objects = ls; // So assignment is OK 
        // Compiles and runs without complaint: 
        objects[1] = new ArrayList<Integer>(); 

        // However, if your needs are straightforward it is 
        // possible to create an array of generics, albeit 
        // with an "unchecked" warning: 
        List<BerylliumSphere>[] spheres = 
           (List<BerylliumSphere>[])new List[10]; 
        for(int i = 0; i < spheres.length; i++) 
           spheres[i] = new ArrayList<BerylliumSphere>(); 
    } 
}

Once you have a reference to a List[], you can see that you get some compile-time checking. The problem is that arrays are covariant, so a List[] is also an Object[], and you can use this to assign an ArrayList into your array, with no error at either compile time or run time.

If you know you’re not going to upcast and your needs are relatively simple, however, it is possible to create an array of generics, which will provide basic compile-time type checking. However, a generic container will virtually always be a better choice than an array of generics.

关于java - 在 Java 中创建一个数组来存储泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16415255/

相关文章:

java - 线程实现一个带有列表的for循环迭代

java - 为什么需要在intellij中添加类路径?

java - 可以在 JDBC/MySQL 中检索更新的行吗?

java - WebSocket DeploymentException 连接失败

java - 当可以从另一种类型推断出一种类型时,有没有一种方法可以避免重复泛型类型参数?

Java - 泛型方法的数组参数的类型推断

java - 如何通过Java处理TextInputLayout

java - 获取数组组件的类

java - Java中相同逻辑的泛化方法

java - 将对象数组转换为泛型类型