Reputation:
I'm having trouble understanding this bit of code in java.util.Arrays in openjdk. I'm curious why this code uses reflection (Array.newInstance) and why it checks to see if the types are the same? Why can't it just do T[] copy = (T[]) new Object[newLength] even if the type T and U differ?
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
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;
}
Upvotes: 1
Views: 857
Reputation: 14169
You cannot instantiate an Array from a generic type like this new T[newLength]
. So all you can do is new Object[newLength]
. But Arrays do store information about the item type in order to be able to throw ArrayStoreException, which would be lost in this case.
Upvotes: 0
Reputation: 1502686
It can - but then you'd end up with an Object[]
even if you'd asked for a String[]
. So this should fail:
String[] strings = Arrays.copyOf(existingArray, 10, String[].class);
Object[] objects = strings;
objects = new Object();
... but it wouldn't if Array.copyOf
always actually returned an Object[]
.
Upvotes: 4