Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

downcasting an array in java (remove the unchecked warning game)

I have a dumb silly question, but sometimes you have to ask them anyways.

I got an Object[] instance in my left hand (it comes from non-generic swing) and a method that accepts a let's say Integer[] as its argument (in my case it's actually a vararg) in my right hand. I'm sure of the content of the array (or I'm ready to pay the price if I'm wrong).

So basically I wrote that :

private static <U, T extends U> T[] cast(final U[] input, final Class<T> newType) {
    //noinspection unchecked
    final T[] result = (T[]) Array.newInstance(newType, input.length);
    System.arraycopy(input, 0, result, 0, input.length);
    return result;
}

can you remove the unchecked warning, without unplugging it ?

why haven't Array.newInstance() been genericized ?

like image 921
nraynaud Avatar asked Jun 29 '26 13:06

nraynaud


1 Answers

why haven't Array.newInstance() been genericized ?

It may be related to generics only being implemented for reference types. Array.newInstance( int.class, 42 ) is perfectly legal, Class<int> is not. With that limitation, there wasn't a backwards compatible way of making it type generic.

The java.util.Arrays class works round this by providing multiple overloads for each primitive type. So this works:

private static <U, T extends U> T[] cast ( final U[] input, final T[]  prototype ) {
    final T[] result = Arrays.copyOf ( prototype, input.length );
    System.arraycopy(input, 0, result, 0, input.length);
    return result;
}

If you don't mind passing in an empty array instead of the class object, it avoids the cast.

like image 139
Pete Kirkham Avatar answered Jul 01 '26 01:07

Pete Kirkham