复制泛型数组

Copying an array of generic type

我想将 ArrayList class 重写为自定义 class。 我尝试不使用任何 java 内置函数而只使用 java 的基本功能来执行此操作。 我为 MyArrayList.toArray 方法编写了这部分代码:

public Object[] toArray() {
    E[] array = (E[]) new Object[size];
    for (int i = 0; i < size; ++i) {
        array[i] = data[i];
    }
    return array;
}

但是您可能知道,它会抛出 ArrayStoreException
然后我查看了 ArrayList class 的 OpenJDK6 实现,发现 Arrays.copyOf();System.arraycopy(); 的用法不是我想要的。

谁能帮我写这个方法,只使用 java 本机功能?

您将无法绕过 vanilla Java 中的 ArrayStoreException,因为它可以防止程序员将无法放入的数组放入数组中一个数组。

Recall from the JLS that this is being checked and enforced at runtime. Since generic types aren't reifiable,JVM 明确禁止创建数组。

If the type of the value being assigned is not assignment-compatible (§5.2) with the component type, an ArrayStoreException is thrown.

If the component type of an array were not reifiable (§4.7), the Java Virtual Machine could not perform the store check described in the preceding paragraph. This is why an array creation expression with a non-reifiable element type is forbidden (§15.10). One may declare a variable of an array type whose element type is non-reifiable, but assignment of the result of an array creation expression to the variable will necessarily cause an unchecked warning (§5.1.9).

System#arraycopy 通过作弊来解决这个问题。

  • 这是一个 native 方法,意味着在纯 Java 中没有实现;它是用 C 语言编写的。

  • 如果数组的原始组件不匹配,或者您正在混合原始组件数组和参考组件数组,它只会抛出 ArrayStoreException