您将如何重构Arrays.copyOf()方法以删除@SuppressWarnings(“ unchecked”)批注?

问题描述 投票:0回答:1

[我正在Java中查看Arrays类,发现在下面的代码中使用了@SuppressWarnings(“ unchecked”)批注。

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

您将如何重构以下代码以删除@SuppressWarnings(“ unchecked”)注释?

java arrays generics
1个回答
0
投票

这里。

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = newType.cast(
    Array.newInstance(newType.getComponentType(), newLength)
);

但是它没有那么快,这对于此方法很重要。

© www.soinside.com 2019 - 2024. All rights reserved.