概要
用数组对象的getClass方法获取数据的类类型,在通过Class.getComponentType获取数组元素类型。
public static <T> T[] toArray(T...a) {
List<T> list = new ArrayList<>();
Collections.addAll(list, a);
T[] r = (T[])java.lang.reflect.Array
.newInstance(a.getClass().getComponentType(), 0);
return list.toArray(r);
}
JDK Class.getComponent方法签名如下
/**
* Returns the {@code Class} representing the component type of an
* array. If this class does not represent an array class this method
* returns null.
*
* @return the {@code Class} representing the component type of this
* class if this class is an array
* @see java.lang.reflect.Array
* @since JDK1.1
*/
public native Class<?> getComponentType();
JDK ArrayList.toArray方法签名如下:
// 因此调用List.toArray方法时,传入一个数组size=0的对象即可
// 如list.toArray(new String[0]);
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}
Arrays.copyOf方法签名如下:
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
List.toArray() VS List.toArray(T[])
list.toArray是直接把集合转换数组,返回Object类型数组,会导致泛型丢失,导致后续可能需要类型转换
list.toArray(T) 返回泛型数组,入参的数组大小建议为原始List的Size(实际测试下来,性能最佳)