Wednesday, February 09, 2005

Re: Creating an array from a generic Java collection

I'm reading Paul's post on arrays and generics and although I don't have an answer to his interesting question, I did find this trick today for narrowing a Java array as a one liner using a List as an intermediate. The trick depends on List using generics:

I have an Certificate[] array for a private key from a key store. I happen to know that all of the array elements are actually X509Certificate and I'm calling into an undocumented API in the JDK which requires an array of such a critter. What's the easiest thing to do?

public static X509Certificate[] narrowToX509(final Certificate[] certificates) {
    return Arrays.asList(certificates).toArray(
            new X509Certificate[certificates.length]);
}

As I explained to a coworker, Java arrays are not related to the object types they hold: just because SubFoo extends Foo does not mean SubFoo[] extends Foo[]. But all arrays do extend java.lang.Object.

UPDATE: Although my trick is still just as useful, my comment about it depending on generics is completely crocked. It is true that asList is generified, but that does not make the trick work.

No comments: