In this post under Java collections, I will show with example the purpose of “Arrays” class “copyOfRange” method.
In the previous post under Java collections, I showed with example the purpose of “Arrays” class “copyOf” method. This method copies all the elements of input array to destination array.
But what if we want to copy only a subset of elements from the input array.
That is where “copyOfRange” method comes into picture.
“copyOfRange” methods copies all the elements coming under the specifed range to the destination array.
It takes three parameters as mentioned below
1) input array
2) starting index (included)
3) ending index (excluded)
The method returns a new array of same type as the input array, containing the copied elements.
Below is the main code for your reference
Main class
1 package core.collection;
2
3 import java.util.Arrays;
4
5 public class ArraysCopyOfRangeExample {
6 public static void main(String[] args) {
7 int[] intInputArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
8 int[] outputArray = Arrays.copyOfRange(intInputArray, 4, 6);
9
10 String result = Arrays.toString(outputArray);
11 System.out.println("First operation: " + result);
12
13 outputArray = Arrays.copyOfRange(intInputArray, 3, 12);
14
15 result = Arrays.toString(outputArray);
16 System.out.println("Second operation: " + result);
17 }
18 }
In the above code, at line 7, I create an array of type integer and populate it.
At line 8, I create an output array.
At line 8, I call “copyOfRange” and tell it copy elements from index 4 to 6 present in “intInputArray”
At line 13, I again call “copyOfRange” and tell it copy elements from index 3 to 12 present in “intInputArray”.
Note here the ending index is more or beyond the ending index of the input array. In that case, the output array will have default values based on the type of the array for remaining positions.
In this way, we can use “copyOfRange” method.
Below is the output
Output
First operation: [5, 6]
Second operation: [4, 5, 6, 7, 8, 9, 0, 0, 0]