I noticed that in Java Array.newInstance() , Object returned, not T[] . This is understandable since this method was introduced before Java supports generic types.
However, it is unexpected that there is no equivalent general version of this. Java 7 Arrays.copyOf not the same - it copies the contents of the parameter, and does not create a new dummy array (with all null objects inside).
Since implementing this seems trivial, is there some reason not adding it to the JRE? or i just can't find it?
UPDATE
It seems that I will provide my own "trivial" implementation to prevent misunderstanding of the issue.
class MyArrayUtil { //Generic version for classes @SuppressWarnings("unchecked") public static <T> T[] newArrayOf(T[] t, int len){ return (T[]) Array.newInstance(t.getClass().getComponentType(), len); } //For array of int public static int[] newArrayOf(int[] t, int len){ return new int[len]; } //For other primitive types... }
I am not sending this code as an answer because it is not the answer to the question. The question is about the reason and / or existing code, and not how to implement it.
UPDATE
I updated the code to make it look like Arrays.copyOf , and the advantage is that the programmer can simply change the type of the parameter to set up the code for another type. I also ruled out using Array.newInstance for primitive types.
java arrays generics
Earth engine
source share