概要

用数组对象的getClass方法获取数据的类类型,在通过Class.getComponentType获取数组元素类型。

  1. public static <T> T[] toArray(T...a) {
  2. List<T> list = new ArrayList<>();
  3. Collections.addAll(list, a);
  4. T[] r = (T[])java.lang.reflect.Array
  5. .newInstance(a.getClass().getComponentType(), 0);
  6. return list.toArray(r);
  7. }

JDK Class.getComponent方法签名如下

  1. /**
  2. * Returns the {@code Class} representing the component type of an
  3. * array. If this class does not represent an array class this method
  4. * returns null.
  5. *
  6. * @return the {@code Class} representing the component type of this
  7. * class if this class is an array
  8. * @see java.lang.reflect.Array
  9. * @since JDK1.1
  10. */
  11. public native Class<?> getComponentType();

JDK ArrayList.toArray方法签名如下:

  1. // 因此调用List.toArray方法时,传入一个数组size=0的对象即可
  2. // 如list.toArray(new String[0]);
  3. public <T> T[] toArray(T[] a) {
  4. if (a.length < size)
  5. // Make a new array of a's runtime type, but my contents:
  6. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
  7. System.arraycopy(elementData, 0, a, 0, size);
  8. if (a.length > size)
  9. a[size] = null;
  10. return a;
  11. }

Arrays.copyOf方法签名如下:

  1. public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
  2. @SuppressWarnings("unchecked")
  3. T[] copy = ((Object)newType == (Object)Object[].class)
  4. ? (T[]) new Object[newLength]
  5. : (T[]) Array.newInstance(newType.getComponentType(), newLength);
  6. System.arraycopy(original, 0, copy, 0,
  7. Math.min(original.length, newLength));
  8. return copy;
  9. }

List.toArray() VS List.toArray(T[])

list.toArray是直接把集合转换数组,返回Object类型数组,会导致泛型丢失,导致后续可能需要类型转换
list.toArray(T) 返回泛型数组,入参的数组大小建议为原始List的Size(实际测试下来,性能最佳)