ArrayUtils { @SuppressWarnings("unchecked") public static <T> T[] copyOfRange(T[] in, int start, int end) { int length = end - start; if (length < 0) { throw new IllegalArgumentException("end < start"); } T[] out = (T[]) Array.newInstance(in.getClass().getComponentType(), length); if (length > 0) { System.arraycopy(in, start, out, 0, Math.min(length, in.length - start)); } return out; }  static int[] copyOf(int[] in, int length); @SuppressWarnings("unchecked") static T[] copyOf(T[] in, int length); @SuppressWarnings("unchecked") static T[] copyOfRange(T[] in, int start, int end); static String toString(Object[] a);  }
@Test public void testCopyOfRangeGeneric() { assertArrayEquals(new String[] {}, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 0, 0)); assertArrayEquals(new String[] { "1" }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 0, 1)); assertArrayEquals(new String[] { "1", "2" }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 0, 2)); assertArrayEquals(new String[] { "1", "2", "3" }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 0, 3)); assertArrayEquals(new String[] { "1", "2", "3", null }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 0, 4)); assertArrayEquals(new String[] {}, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 1, 1)); assertArrayEquals(new String[] { "2" }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 1, 2)); assertArrayEquals(new String[] { "2", "3" }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 1, 3)); assertArrayEquals(new String[] { "2", "3", null }, ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 1, 4)); try { ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, 1, 0); fail("Should have thrown"); } catch (IllegalArgumentException e) { } try { ArrayUtils.copyOfRange(new String[] { "1", "2", "3" }, -1, 4); fail("Should have thrown"); } catch (ArrayIndexOutOfBoundsException e) { } }