开发者社区> 问答> 正文

阿里Java技术规范-集合处理toArray(T[] arr)

集合处理中第6条要求传一个类型一致的空数组。

使用集合转数组的方法,必须使用集合的toArray(T[] array),传入的是类型完全一 致、长度为0的空数组

看toArray(T[] arr) 的源码 :

    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;
    }

最终还是调用 System.arraycopy(...)方法。对此不能理解,为什么不直接传length==size的数组呢

展开
收起
1907741823559501 2020-03-21 11:57:49 1030 0
1 条回答
写回答
取消 提交回答
  • 不知道是不是深浅拷贝的问题?

    2020-03-21 16:36:12
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载