How to create a sub-array from another array? Is there a method that takes the indexes from the first array such as:
methodName(object array, int start, int
The code is correct so I'm guessing that you are using an older JDK. The javadoc for that method says it has been there since 1.6. At the command line type:
java -version
I'm guessing that you are not running 1.6
Arrays.copyOfRange(..)
was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)
JDK >= 1.8
I agree with all the answers above. There is also a nice way with Java 8 Streams:
int[] subArr = IntStream.range(startInclusive, endExclusive)
.map(i -> src[i])
.toArray();
The benefit about this is, it can be useful for many different types of "src" array and helps to improve writing pipeline operations on the stream.
Not particular about this question, but for example, if the source array was double[]
and we wanted to take average()
of the sub-array:
double avg = IntStream.range(startInclusive, endExclusive)
.mapToDouble(index -> src[index])
.average()
.getAsDouble();