Skip to content

Instantly share code, notes, and snippets.

@Michael0x2a
Last active June 22, 2016 05:47
Show Gist options
  • Save Michael0x2a/8c6e2811dd8fd39fc52a71575478c82e to your computer and use it in GitHub Desktop.
Save Michael0x2a/8c6e2811dd8fd39fc52a71575478c82e to your computer and use it in GitHub Desktop.
/**
* Copies the specified range of the specified array into a new array.
* The initial index of the range ("from") must lie between zero
* and "original.length", inclusive. The value at
* "original[from]" is placed into the initial element of the copy
* (unless "from == original.length" or "from == to").
* Values from subsequent elements in the original array are placed into
* subsequent elements in the copy. The final index of the range
* ("to"), which must be greater than or equal to "from",
* may be greater than "original.length", in which case
* "null" is placed in all elements of the copy whose index is
* greater than or equal to "original.length - from". The length
* of the returned array will be "to - from".
*
* Parameters:
* original: the array from which a range is to be copied
* from: the initial index of the range to be copied, inclusive
* to: the final index of the range to be copied, exclusive.
* (This index may lie outside the array.)
*
* Return value:
* a new array containing the specified range from the original array,
* truncated or padded with null characters to obtain the required length
*
* Exceptions thrown:
* ArrayIndexOutOfBoundsException if "from < 0" or "from > original.length"
* IllegalArgumentException if "from > to"
* NullPointerException if "original" is null
*/
public static char[] copyOfRange(char[] original, int from, int to) {
int newLength = to - from;
if (newLength < 0)
throw new IllegalArgumentException(from + " > " + to);
char[] copy = new char[newLength];
System.arraycopy(original, from, copy, 0,
Math.min(original.length - from, newLength));
return copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment