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];
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];
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 andoriginal.length, inclusive. The value atoriginal[from]is placed into the initial element of the copy (unlessfrom == original.lengthorfrom == 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 thanoriginal.length, in which case null is placed in all elements of the copy whose index is greater than or equal tooriginal.length - from. The length of the returned array will beto - 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);
Arrays.copyOfRange(elements, i, i + n) would exclude elements[i+n]. To include it, you should use Arrays.copyOfRange(elements, i, i+n+1). But maybe the OP intended to copy n elements in which case your answer is correct.You will use Arrays.copyOfRange().
Here is an example:
String[] original = some array;
String[] grp = Arrays.copyOfRange(original, i, i + n);
The Javadocs for the Arrays class has lots of information about the method:
+1 to include elements[i+n] in the range.Use Arrays.copyOfRange():
String[] grp = Arrays.copyOfRange(grp, i, i+n);
As the name implies grp will be a copy of the original array and not a view into it. You can't have views into the array, for that you'd need to use a collection. Generally speaking collections are the more powerful and flexible, high-level alternative to arrays.