Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

I have the next snippet of code:

Certificate[] a = myFavouriteKeystore.getCertificateChain();

but I need to pass it to a method with the following signature:

void setCertificateChain(X509Certificate[] chain);

Can I do the following?:

setCertificateChain((X509certificate[]) a);

IDE(eclipse) accepts it and I assume that compiler does also, but my guess is that I'll get a ClassCastException even in the case that all the array elements are of class X509Certificate or a subclass of it.

like image 732
Luis Colorado Avatar asked May 20 '19 08:05

Luis Colorado


2 Answers

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.

like image 67
Eugene Avatar answered Nov 15 '22 18:11

Eugene


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.

like image 32
Luis Colorado Avatar answered Nov 15 '22 18:11

Luis Colorado