Java Language Casting Arrays


Example

Arrays are objects, but their type is defined by the type of the contained objects. Therefore, one cannot just cast A[] to T[], but each A member of the specific A[] must be cast to a T object. Generic example:

public static <T, A> T[] castArray(T[] target, A[] array) {
    for (int i = 0; i < array.length; i++) {
        target[i] = (T) array[i];
    }
    return target;
}

Thus, given an A[] array:

T[] target = new T[array.Length];
target = castArray(target, array);

Java SE provides the method Arrays.copyOf(original, newLength, newType) for this purpose:

Double[] doubles = { 1.0, 2.0, 3.0 };
Number[] numbers = Arrays.copyOf(doubles, doubles.length, Number[].class);