337

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);
    }
}
J.Olufsen
  • 12,749
  • 41
  • 115
  • 176
Gain
  • 3,453
  • 4
  • 18
  • 10

8 Answers8

368

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

Flow
  • 22,860
  • 14
  • 95
  • 151
jmj
  • 232,312
  • 42
  • 391
  • 431
  • 3
    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 Oct 09 '13 at 21:30
  • @NuclearPeon Thank you!!! Would have taken me a long while before I figured it out myself. Eclipse automatically imported `org.bouncycastle.util.Arrays`. – Snackoverflow Jul 19 '17 at 12:30
144

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

Bozho
  • 572,413
  • 138
  • 1,043
  • 1,132
21

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
KNU
  • 2,454
  • 5
  • 24
  • 37
Gerco Dries
  • 6,610
  • 1
  • 24
  • 34
12

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();
enator
  • 2,231
  • 1
  • 25
  • 41
  • 3
    Good idea to use streams. One could also use `Stream.of(source).skip(start).limit(count).toArray(Foo[]::new)`. – Martin Jan 04 '22 at 21:41
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

Alessandro Muzzi
  • 733
  • 1
  • 11
  • 26
3
int newArrayLength = 30; 

int[] newArray = new int[newArrayLength];

System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);
Riduidel
  • 21,635
  • 13
  • 81
  • 178
Milan Jaros
  • 1,057
  • 16
  • 20
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

Merky
  • 496
  • 2
  • 4
1

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

AlexR
  • 111,884
  • 15
  • 126
  • 200