Get Slice of a Primitive Array in Java

In this post, we will see how to get slice of a primitive array in Java. In other words, get subarray of a given primitive array between specified indexes.


 

1. Arrays.copyOfRange()

The idea is to use Arrays.copyOfRange() to copy the specified range of the specified array into a new array. Arrays class provides several overloaded versions of copyOfRange() method, for all primitive types.

 

Download   Run Code

Output:

[2, 3, 4, 5]

 

2. Java 8

From Java 8 onwards, we can simply get a Stream of elements between the specified range and then call toArray() method to accumulate elements of the stream into corresponding primitive array.

 

Download   Run Code

Output:

[2, 3, 4, 5]

 

3. ArrayUtils.subarray() in Apache Commons

Apache Commons provides ArrayUtils class that has several utility methods for primitive arrays. It has subarray() method that can produce a primitive subarray containing the elements between specified indexes.

 

Download

Output:

[2, 3, 4, 5]

 

4. Naive

Finally, we can also write our own custom method which creates a new array and copy the elements from original array to new array by iterating over the array between specified indexes.

 

Download   Run Code

Output:

[2, 3, 4, 5]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz