Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: is there an easy way to select a subset of an array?

Tags:

java

I have a String[] that has at least 2 elements.

I want to create a new String[] that has elements 1 through the rest of them. So.. basically, just skipping the first one.

Can this be done in one line? easily?

like image 234
NullVoxPopuli Avatar asked Jan 27 '11 21:01

NullVoxPopuli


People also ask

How do you select a subset of an array?

Use the System. arraycopy() Method to Get the Subset of an Array. System. arraycopy() method can copy a subset from an array with given beginning and ending indexes.

Is there array slicing in Java?

In Java, array slicing is a way to get a subarray of the given array.

How do you get a subarray from an array?

slice() The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included) where start and end represent the index of items in that array. The original array will not be modified. Basically, slice lets you select a subarray from an array.


1 Answers

Use copyOfRange, available since Java 1.6:

Arrays.copyOfRange(array, 1, array.length); 

Alternatives include:

  • ArrayUtils.subarray(array, 1, array.length) from Apache commons-lang
  • System.arraycopy(...) - rather unfriendly with the long param list.
like image 167
Bozho Avatar answered Sep 20 '22 21:09

Bozho