Get only part of an Array in Java?

JavaArrays

Java Problem Overview


I have an array of Integers in Java, I would like use only a part of it. I know in Python you can do something like this array[index:] and it returns the array from the index. Is something like this possible in Java.

Java Solutions


Solution 1 - Java

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)


Solution 2 - Java

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);

Solution 3 - Java

Yes, you can use Arrays.copyOfRange

It does about the same thing (note there is a copy : you don't change the initial array).

Solution 4 - Java

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.

Solution 5 - Java

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 at original[from] is placed into the initial element of the copy (unless from == original.length or from == 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 to from, may be greater than original.length, in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - 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]);
    }

}

Solution 6 - Java

Check out copyOfRange; and example:

int[] arr2 = Arrays.copyOfRange(arr,0,3);

Solution 7 - Java

You can use something like this: Arrays#copyOfRange

Solution 8 - Java

public static int[] range(int[] array, int start, int end){
        int returner[] = new int[end-start];
        for(int x = 0; x <= end-start-1; x++){
            returner[x] = array[x+start];
        }
        return returner;
    }

this is a way to do the same thing as Array.copyOfRange but without importing anything

Solution 9 - Java

You can use subList(int fromIndex, int toIndex) method on your integers arr, something like this:

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> arr = new ArrayList<>();
        arr.add(1);
        arr.add(2);
        arr.add(3);
        arr.add(4);
        List<Integer> partialArr = arr.subList(1, 3);
        
        // print the subArr
        for (Integer i: partialArr)
            System.out.println(i + " ");
    }
}

Output will be: 2 3.

Note that subList(int fromIndex, int toIndex) method performs minus 1 on the 2nd variable it receives (var2 - 1), i don't know exactly why, but that's what happens, maybe to reduce the chance of exceeding the size of the array.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBorut FlisView Question on Stackoverflow
Solution 1 - JavaeliasView Answer on Stackoverflow
Solution 2 - JavaK-balloView Answer on Stackoverflow
Solution 3 - JavaDenys SéguretView Answer on Stackoverflow
Solution 4 - JavaStvnBrkdllView Answer on Stackoverflow
Solution 5 - JavaJustin EthierView Answer on Stackoverflow
Solution 6 - JavadcpView Answer on Stackoverflow
Solution 7 - JavaCBredlowView Answer on Stackoverflow
Solution 8 - JavaPersons123View Answer on Stackoverflow
Solution 9 - JavaA. AbView Answer on Stackoverflow