1

I was looking inside Arrays class in java and saw that @SuppressWarnings("unchecked") annotation is being used in the following code.

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    @SuppressWarnings("unchecked")
    T[] copy = ((Object)newType == (Object)Object[].class)
        ? (T[]) new Object[newLength]
        : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}

How would you refactor the following code in order to remove @SuppressWarnings("unchecked") annotation?

IonKat
  • 216
  • 4
  • 10
  • 3
    You can't, [because you can't create array of generic type in java](https://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java). So you would have to typecast. – Adwait Kumar Feb 08 '20 at 16:53
  • 1
    @AdwaitKumar But we do know the runtime type of `T[]` here. The problem is that there isn't an `Array.newInstance` with an appropriate signature. – Tom Hawtin - tackline Feb 08 '20 at 17:08
  • 2
    @TomHawtin-tackline The problem is not the *signature* of `Array.newInstance(Class>, int)`, but its *return type*. It’s declared to return `Object` to cater for the case where the element type is a primitive type so the array type is not a subtype of `Object[]`. – Ole V.V. Feb 08 '20 at 19:08
  • Yeah, signature is the wrong term. I mean to include the return type, the type of `componentType` and that it is the `length` version not `dimensions` (which has *another* reason not to return `T[]`). Perhaps *signatures* is better. – Tom Hawtin - tackline Feb 09 '20 at 01:19

1 Answers1

1

Here.

public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
T[] copy = newType.cast(
    Array.newInstance(newType.getComponentType(), newLength)
);

But it is not as fast, which is important for this method.

Tom Hawtin - tackline
  • 139,906
  • 30
  • 206
  • 293