ArrayUtils { public static int[] copyOf(int[] in, int length) { int[] out = new int[length]; if (length > 0) { System.arraycopy(in, 0, out, 0, Math.min(length, in.length)); } 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 testCopyOf() { assertArrayEquals(new int[] {}, ArrayUtils.copyOf(new int[] { 1, 2, 3 }, 0)); assertArrayEquals(new int[] { 1 }, ArrayUtils.copyOf(new int[] { 1, 2, 3 }, 1)); assertArrayEquals(new int[] { 1, 2 }, ArrayUtils.copyOf(new int[] { 1, 2, 3 }, 2)); assertArrayEquals(new int[] { 1, 2, 3 }, ArrayUtils.copyOf(new int[] { 1, 2, 3 }, 3)); assertArrayEquals(new int[] { 1, 2, 3, 0 }, ArrayUtils.copyOf(new int[] { 1, 2, 3 }, 4)); try { ArrayUtils.copyOf(new int[] { 1, 2, 3 }, -1); fail("Should have thrown"); } catch (NegativeArraySizeException e) { } }
@Test public void testCopyOfGeneric() { assertArrayEquals(new String[] {}, ArrayUtils.copyOf(new String[] { "1", "2", "3" }, 0)); assertArrayEquals(new String[] { "1" }, ArrayUtils.copyOf(new String[] { "1", "2", "3" }, 1)); assertArrayEquals(new String[] { "1", "2" }, ArrayUtils.copyOf(new String[] { "1", "2", "3" }, 2)); assertArrayEquals(new String[] { "1", "2", "3" }, ArrayUtils.copyOf(new String[] { "1", "2", "3" }, 3)); assertArrayEquals(new String[] { "1", "2", "3", null }, ArrayUtils.copyOf(new String[] { "1", "2", "3" }, 4)); try { ArrayUtils.copyOf(new String[] { "1", "2", "3" }, -1); fail("Should have thrown"); } catch (NegativeArraySizeException e) { } }