Collection中的toArray(T[] a)方法

160 阅读1分钟

原以为集合中提供了带数组参数的转换方法会严格要求数组的长度,结果并不是这样的。

  • 看源码:
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;
    }
  1. 当参数数组长度小于队列长度时,强行转换为数组,只是多做了强制类型转换。
  2. 当参数数组长度小于队列长度时,强行转换为数组,使用null补齐数组长度。

所以一般使用一个0长数组即可

   list.toArray(new Object[0]);