Get only part of an Array in Java? [duplicate]
The length of an array in Java is immutable. So, you need to copy the desired part into a new array.
Use copyOfRange
method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
startIndex is the initial index of the range to be copied, inclusive.
endIndex is the final index of the range to be copied, exclusive. (This index may lie outside the array)
E.g.:
//index 0 1 2 3 4
int[] arr = {10, 20, 30, 40, 50};
Arrays.copyOfRange(arr, 0, 2); // returns {10, 20}
Arrays.copyOfRange(arr, 1, 4); // returns {20, 30, 40}
Arrays.copyOfRange(arr, 2, arr.length); // returns {30, 40, 50} (length = 5)
You could wrap your array as a list, and request a sublist of it.
MyClass[] array = ...;
List<MyClass> subArray = Arrays.asList(array).subList(index, array.length);
Yes, you can use Arrays.copyOfRange
It does about the same thing (note there is a copy : you don't change the initial array).
You can try:
System.arraycopy(sourceArray, 0, targetArray, 0, targetArray.length);// copies whole array
// copies elements 1 and 2 from sourceArray to targetArray
System.arraycopy(sourceArray, 1, targetArray, 0, 2);
See javadoc for System.
If you are using Java 1.6 or greater, you can use Arrays.copyOfRange
to copy a portion of the array. From the javadoc:
Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and
original.length
, inclusive. The value atoriginal[from]
is placed into the initial element of the copy (unlessfrom == original.length
orfrom == to
). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to
), which must be greater than or equal tofrom
, may be greater thanoriginal.length
, in which casefalse
is placed in all elements of the copy whose index is greater than or equal tooriginal.length - from
. The length of the returned array will beto - from
.
Here is a simple example:
/**
* @Program that Copies the specified range of the specified array into a new
* array.
* CopyofRange8Array.java
* Author:-RoseIndia Team
* Date:-15-May-2008
*/
import java.util.*;
public class CopyofRange8Array {
public static void main(String[] args) {
//creating a short array
Object T[]={"Rose","India","Net","Limited","Rohini"};
// //Copies the specified short array upto specified range,
Object T1[] = Arrays.copyOfRange(T, 1,5);
for (int i = 0; i < T1.length; i++)
//Displaying the Copied short array upto specified range
System.out.println(T1[i]);
}
}