Copying a generic array

I want to rewrite the class ArrayList

as a custom class. I tried to do this without using ANY java's built-in functions and just using the basic java capabilities. I wrote this piece of code for the method MyArrayList.toArray

:

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

      

But, as you know, he throws away ArrayStoreException

.
Then I took a look at the implementation of the OpenJDK6 ArrayList class and it was using Arrays.copyOf();

and System.arraycopy();

which I don't want.

Can anyone help me write this method ONLY using native Java capabilities?

+3


source to share


1 answer


You won't be able to get around ArrayStoreException

in vanilla Java, as that should prevent the programmer from putting something into an array that simply can't be put into an array.

Call from the JLS that this is checked and executed at runtime. Since generic types are not persisted , the JVM explicitly disallows array creation.

If the type of the assigned value is not compatible with the assignment (ยง5.2) with the type of the component, then a ArrayStoreException

.

If the type of the array component was not verifiable (ยง4.7), the Java Virtual Machine could not perform the storage validation described in the previous paragraph. This is why the expression to create an array with a non-recoverable element type is prohibited (ยง15.10). It is possible to declare an array-type variable whose element type is unrecoverable, but assigning the result of an array-creation expression to a variable will necessarily result in an uncontrolled warning (ยง5.1.9).



System#arraycopy

turns it around, cheating a little.

  • It is a native method, which means there is no implementation in pure Java; it's written in C. Instead.

  • It only generates ArrayStoreException

    if the primitive components of the arrays are not the same, or you are mixing primitive component arrays and reference component arrays.

+2


source







All Articles