Downcasting array in java (remove unverified warning game)

I have a stupid stupid question, but sometimes you have to ask them anyway.

I have an instance of Object [] in my left hand (it comes from a non-generic swing) and a method that takes a say Integer [] clause as an argument (in my case it is actually vararg) in my right hand, I am sure of the contents of the array ( or am I willing to pay the price if I am wrong).

So basically I wrote this:

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 a warning without disconnecting it?

why wasn't Array.newInstance () generalized?

+3
source share
2 answers

why wasn't Array.newInstance () generalized?

, . Array.newInstance( int.class, 42 ) , Class<int> . .

java.util.Arrays , . , :

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;
}

, .

+2

: :

@SuppressWarnings("unchecked")

: :

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];
}
0

Source: https://habr.com/ru/post/1718937/


All Articles