如何在运行时实例化给定数组类型的Java数组?
时间:2020-03-05 18:57:15 来源:igfitidea点击:
在Java集合框架中,集合接口声明以下方法:
<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.
如果要实现此方法,将如何创建a类型的数组(仅在运行时才知道)?
解决方案
回答
Array.newInstance(Class componentType, int length)
回答
通过查看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; }
回答
使用静态方法
java.lang.reflect.Array.newInstance(Class<?> componentType, int length)
可以在此处找到有关其用法的教程:
http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html
回答
要创建一个通用类型的新数组(仅在运行时才知道),我们必须创建一个Objects数组,然后将其强制转换为通用类型,然后按原样使用它。这是Java(擦除)的泛型实现的限制。
T[] newArray = (T[]) new Object[X]; // where X is the number of elements you want.
然后,该函数采用给定的数组(a)并使用它(事先检查其大小)或者创建一个新数组。