如何在运行时实例化给定数组类型的 Java 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/77387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:58:13  来源:igfitidea点击:

How to instantiate a Java array given an array type at runtime?

javaarrayscollections

提问by Sam

In the Java collections framework, the Collection interface declares the following method:

在 Java 集合框架中,Collection 接口声明了以下方法:

<T> T[] toArray(T[] a)

Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.

<T> T[] toArray(T[] a)

返回一个包含此集合中所有元素的数组;返回数组的运行时类型是指定数组的类型。如果集合适合指定的数组,则在其中返回。否则,将使用指定数组的运行时类型和此集合的大小分配一个新数组。

If you wanted to implement this method, how would you create an array of the type of a, known only at runtime?

如果你想实现这个方法,你将如何创建一个a类型的数组,只在运行时知道?

回答by user9116

Use the static method

使用静态方法

java.lang.reflect.Array.newInstance(Class<?> componentType, int length)

A tutorial on its use can be found here: http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html

可以在此处找到有关其使用的教程:http: //java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html

回答by SCdF

By looking at how ArrayList does it:

通过查看 ArrayList 如何做到这一点:

public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
    System.arraycopy(elementData, 0, a, 0, size);
    if (a.length > size)
        a[size] = null;
    return a;
}

回答by Arno

Array.newInstance(Class componentType, int length)

回答by Christian P.

To create a new array of a generic type (which is only known at runtime), you have to create an array of Objects and simply cast it to the generic type and then use it as such. This is a limitation of the generics implementation of Java (erasure).

要创建泛型类型的新数组(仅在运行时已知),您必须创建一个对象数组,然后将其简单地转换为泛型类型,然后按原样使用它。这是 Java 泛型实现的一个限制(擦除)。

T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.

The function then takes the array given (a) and uses it (checking it's size beforehand) or creates a new one.

然后该函数采用给定的数组 (a) 并使用它(事先检查它的大小)或创建一个新数组。