为啥要Arrays#CopyOf要单独处理Object这种类型?

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;

}

为啥要单独处理Object数组,而不写成:

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {

@SuppressWarnings("unchecked")

T[] copy = (T[]) Array.newInstance(newType.getComponentType(), newLength);

System.arraycopy(original, 0, copy, 0,

Math.min(original.length, newLength));

return copy;

}


回答:

我的理解是在能单独判断newType就是Object[].class的情况下,直接new一个Object[]代价比较小,不需要还走Array.newInstance底层的Array.newArray方法,这是一个native方法,运用的是反射原理,代价比较大。

以上是 为啥要Arrays#CopyOf要单独处理Object这种类型? 的全部内容, 来源链接: utcz.com/p/945197.html

回到顶部