Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array substring

How can I create/instantiate an array to be equal to the substring of another array, where the size of the substring is unknown:

int n; //some number derived somewhere else

String[] grp = elements[i] to elements[i+n];
like image 557
Will Avatar asked Jul 06 '11 13:07

Will


1 Answers

Use Arrays.copyOfRange:

public static <T> T[] copyOfRange(T[] original,
                                  int from,
                                  int to)

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.

The resulting array is of exactly the same class as the original array.

In your case:

String[] grp = Arrays.copyOfRange(elements, i, i + n);
like image 88
NPE Avatar answered Oct 22 '22 20:10

NPE