384

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);
    }
}
0

10 Answers 10

419

You can use

JDK > 1.5

Arrays.copyOfRange(Object[] src, int from, int to)

Javadoc

JDK <= 1.5

System.arraycopy(Object[] src, int srcStartIndex, Object[] dest, int dstStartIndex, int lengthOfCopiedIndices); 

Javadoc

Sign up to request clarification or add additional context in comments.

4 Comments

I was having some issues with not having Object[]s in my Arrays.copyOfRange. Check your imports to ensure you are using java.util.Arrays. Somehow a different Arrays version got imported and I wasted 15 minutes checking JREs and JDKs for the issue.
@NuclearPeon Thank you!!! Would have taken me a long while before I figured it out myself. Eclipse automatically imported org.bouncycastle.util.Arrays.
This is actually a copy of a part of an array. A sub-array would be pointing to the original array like a sub-list. Changing an array element will not affect the original array whereas in a sub-array it would. Also it has performance implications as not only the pointers are copied, but all elements (for objects shallow copy).
I needed to copy an array into an already existing larger array . In my use case, System.arraycopy() was exactly what I needed.
147

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(..)

5 Comments

@Sami either upgrade to 1.6 or see this doc for reference download.oracle.com/javase/1.4.2/docs/api/java/lang/System.html
Which vendor is your JDK from. Sun/Oracle never released a version 4.00.28 and google couldn't find it either.
copyOfRange nulls trailing elements if they are out of source array range instead of allocating a smaller array :(
someone should add in the answer that while "start-index" is inclusive, "end-index" is exclusive
@YanKingYin you are correct--this is precisely what I was reading the comments for :)
22

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

Comments

17

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();

1 Comment

Good idea to use streams. One could also use Stream.of(source).skip(start).limit(count).toArray(Foo[]::new).
8

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

Comments

4
int newArrayLength = 30; 

int[] newArray = new int[newArrayLength];

System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);

Comments

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

Comments

2

For Java >= 1.8

Arrays.stream(array, incIndex, exclusiveIndex)

Comments

1

I you are using java prior to version 1.6 use System.arraycopy() instead. Or upgrade your environment.

Comments

0

OP said they didn't want a for loop but in case anyone does:

int[] subArr = new int[end - start];

for (int i = 0; i < end - start; i++){
    subArr[i] = sourceArr[i + start];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.