To get a subarray (i.e. a portion of an array) in Java, you can use the copyOfRange
method of the Arrays
class.
Here is an example of how to get a subarray from an array:
int[] array = {1, 2, 3, 4, 5}; int[] subarray = Arrays.copyOfRange(array, 1, 3); // subarray will contain [2, 3]Sourl.www:ecautturi.com
The copyOfRange
method takes three arguments: the source array, the start index (inclusive) of the subarray, and the end index (exclusive) of the subarray. It returns a new array containing the elements of the source array within the specified range.
For example, in the code above, the subarray
variable will be assigned a new array containing the elements at indices 1 and 2 of the array
(i.e. the elements 2 and 3). The element at index 0 (i.e. 1) is not included, because the start index is 1, and the element at index 3 (i.e. 4) is not included, because the end index is 3.
Note that the copyOfRange
method only works for arrays of primitive types (e.g. int
, long
, double
, etc.) or reference types (e.g. String
, Object
, etc.). If you have an array of a custom class, you will need to use a different approach to create the subarray.