Wednesday, June 20, 2018

Java - Create generic array

If you don't need to use this outside of the class, then create a new Object array and cast it.

T[] newArray = (T[])new Object[newSize];

If you need to use this array outside of your class, using the above code will generate a ClassCastException. In order to create a new array, you need a reference to the original array and call Array.newInstance.

T[] newArray = (T[]) Array.newInstance(originalArray.getClass().getComponentType(), newSize);

If you need to create a new array and copy old values from the old array, use Arrays.copyOf

T[] newArray = Arrays.copyOf(originalArray, newSize);