Java Language Arrays Casting Arrays

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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


Got any Java Language Question?