Reputation: 5132
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 ?
Upvotes: 3
Views: 1400
Reputation: 49311
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.
Upvotes: 2
Reputation: 8318
Short way: Put this above the method to suppress the warning:
@SuppressWarnings("unchecked")
Long way: Loop through and cast each element in turn:
Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
c[i] = (Integer) a[i];
}
Upvotes: 0