EN
Java - copy sub-array
8
points
In this short article, we would like to show how to copy sub-array in Java.
Quick solution:
int[] subarray = Arrays.copyOfRange(array, from, to);
Practical example
In this section, you can find embedded function that lets to copy array part. Function accepts array, start and end indexes.
import java.util.Arrays;
class Program {
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3, 4, 5, 6};
int[] subarray = Arrays.copyOfRange(array, 1, 4);
System.out.println(Arrays.toString(subarray));
}
}
Output:
[2, 3, 4]
Note:
Arrays.copyOfRange()was introduced in Java 1.6.
Alternative solution
Example Program.java file:
public class Program {
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3, 4, 5, 6};
int[] subarray = ArrayUtils.copyArray(array, 1, 4);
System.out.println(Arrays.toString(subarray));
}
}
Output:
[2, 3, 4]
Example ArrayUtils.java file:
import java.util.Arrays;
import java.lang.IllegalArgumentException;
public class ArrayUtils {
public static int[] copyArray(int[] array, int start, int end) {
if (start > end) {
throw new IllegalArgumentException("The start index cannot be greater than the end index.");
}
int[] result = new int[end - start];
System.arraycopy(array, start, result, 0, result.length);
return result;
}
}