Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only part of an Array in Java? [duplicate]

Tags:

java

arrays

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.

like image 416
Borut Flis Avatar asked Jun 12 '12 17:06

Borut Flis


People also ask

How do you copy half an array?

Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.

Is slicing possible in Java?

In Java, array slicing is a way to get a subarray of the given array. Suppose, a[] is an array. It has 8 elements indexed from a[0] to a[7]. In this section, we will learn how to find a slice of an array in Java.


1 Answers

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) 
like image 125
elias Avatar answered Sep 20 '22 14:09

elias