Java tutorial
//package com.java2s; import java.lang.reflect.Array; public class Main { public static <T> T[] ensureExactLength(T[] array, int length) { if (array.length == length) { return array; } T[] newArray = (T[]) Array.newInstance(array.getClass().getComponentType(), length); if (array.length > 0) { System.arraycopy(array, 0, newArray, 0, length); } return newArray; } }