If I cast an array of T to an array of Q (being Q derived from T) does it cast each element in turn?

You will get ClassCastException at runtime, yes.

The cast is like lying to the compiler, saying that you really know what you are doing and even if the compiler can't prove that the cast will work - you are instructing it to trust you.

The compiler listens to you (not in all cases, i.e. you can't tell it to cast a String to an Integer for example, since String is final and can't have sub-classes), but at the same time will inject into the byte code checkcast instructions.


Tested, and it fails with a ClassCastException error:

package test;

public class TestClass {

    public static class A { }
    public static class B extends A { }

    public static void main(String [] args) {
        A[] a = new A[100];
        for (int i = 0; i < a.length; i++) {
            a[i] = new B();
        }
        B[] b = (B[]) a;  /* Error: ClassCastException, even if all elements are of type B */
    }
}

Thanks to @Eugene that so quick answered the question.

NOTE

This agrees with the policy of casting generic containers. For a container derived of a super class only the cast applies if the parameter types match. E.g: Set<A> can be casted to SortedSet<B> only if A and B are the same type.

Tags:

Java