Java tutorial
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import java.lang.reflect.Array; public class Main { /** * Copies the specified array, truncating or padding with nulls (if necessary) * so the copy has the specified length. For all indices that are valid in * both the original array and the copy, the two arrays will contain identical * values. For any indices that are valid in the copy but not the original, * the copy will contain null. Such indices will exist if and only if the * specified length is greater than that of the original array. The * resulting array is of exactly the same class as the original array. * * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with nulls to * obtain the specified length */ public static <T> T[] copyOf(T[] original, int newLength) { @SuppressWarnings({ "unchecked" }) T[] copy = (T[]) Array.newInstance(original.getClass().getComponentType(), newLength); System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength)); return copy; } }