gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:47:08 24 4
gpt4 key购买 nike

假设我必须创建一个数组来存储 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/

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