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 end)
I don't want to go over making loops and making my program suffer.
I keep getting error:
cannot find symbol method copyOfRange(int[],int,int)
This is my code:
import java.util.*;
public class testing
{
public static void main(String [] arg)
{
int[] src = new int[] {1, 2, 3, 4, 5};
int b1[] = Arrays.copyOfRange(src, 0, 2);
}
}
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
Using Apache ArrayUtils downloadable at this link you can easy use the method
subarray(boolean[] array, int startIndexInclusive, int endIndexExclusive)
"boolean" is only an example, there are methods for all primitives java types
Use copyOfRange method from java.util.Arrays class:
int[] newArray = Arrays.copyOfRange(oldArray, startIndex, endIndex);
For more details:
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();
I you are using java prior to version 1.6 use System.arraycopy()
instead. Or upgrade your environment.
Yes, it's called System.arraycopy(Object, int, Object, int, int) .
It's still going to perform a loop somewhere though, unless this can get optimized into something like REP STOSW
by the JIT (in which case the loop is inside the CPU).
int[] src = new int[] {1, 2, 3, 4, 5};
int[] dst = new int[3];
System.arraycopy(src, 1, dst, 0, 3); // Copies 2, 3, 4 into dst
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(..)
int newArrayLength = 30;
int[] newArray = new int[newArrayLength];
System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);
Source: Stackoverflow.com