Get only part of an Array in Java?
To get only a part of an array in Java, you can use the Arrays.copyOfRange()
method, or you can use the System.arraycopy()
method.
Here is an example of how you can use the Arrays.copyOfRange()
method to get a part of an array:
int[] a = {1, 2, 3, 4, 5};
int[] b = Arrays.copyOfRange(a, 1, 3); // b is {2, 3}
The Arrays.copyOfRange()
method takes three arguments: the original array, the start index (inclusive), and the end index (exclusive). It returns a new array that contains the elements of the original array from the start index to the end index.
Here is an example of how you can use the System.arraycopy()
method to get a part of an array:
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[2];
System.arraycopy(a, 1, b, 0, 2); // b is {2, 3}
The System.arraycopy()
method takes five arguments: the source array, the source index, the destination array, the destination index, and the number of elements to copy. It copies the elements of the source array to the destination array, starting from the source index and the destination index, and for the specified number of elements.
I hope this helps! Let me know if you have any questions.