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:
xxxxxxxxxx
1
int[] subarray = Arrays.copyOfRange(array, from, to);
In this section, you can find embedded function that lets to copy array part. Function accepts array, start and end indexes.
xxxxxxxxxx
1
import java.util.Arrays;
2
3
class Program {
4
5
public static void main(String[] args) {
6
7
int[] array = new int[] {1, 2, 3, 4, 5, 6};
8
int[] subarray = Arrays.copyOfRange(array, 1, 4);
9
10
System.out.println(Arrays.toString(subarray));
11
}
12
}
Output:
xxxxxxxxxx
1
[2, 3, 4]
Note:
Arrays.copyOfRange()
was introduced in Java 1.6.
Example Program.java
file:
xxxxxxxxxx
1
public class Program {
2
3
public static void main(String[] args) {
4
5
int[] array = new int[] {1, 2, 3, 4, 5, 6};
6
int[] subarray = ArrayUtils.copyArray(array, 1, 4);
7
8
System.out.println(Arrays.toString(subarray));
9
}
10
}
Output:
xxxxxxxxxx
1
[2, 3, 4]
Example ArrayUtils.java
file:
xxxxxxxxxx
1
import java.util.Arrays;
2
import java.lang.IllegalArgumentException;
3
4
public class ArrayUtils {
5
6
public static int[] copyArray(int[] array, int start, int end) {
7
if (start > end) {
8
throw new IllegalArgumentException("The start index cannot be greater than the end index.");
9
}
10
int[] result = new int[end - start];
11
System.arraycopy(array, start, result, 0, result.length);
12
return result;
13
}
14
}