364

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
  • 13,415
  • 44
  • 120
  • 185
Gain
  • 3,723
  • 4
  • 19
  • 10

10 Answers10

397

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
  • 23,572
  • 15
  • 99
  • 156
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 4
    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
  • 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). – Gunnar Bernstein Feb 17 '23 at 06:38
146

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
  • 588,226
  • 146
  • 1,060
  • 1,140
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
KNU
  • 2,560
  • 5
  • 26
  • 39
Gerco Dries
  • 6,682
  • 1
  • 26
  • 35
16

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,431
  • 2
  • 28
  • 46
  • 6
    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
  • 808
  • 1
  • 12
  • 26
4
int newArrayLength = 30; 

int[] newArray = new int[newArrayLength];

System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);
Riduidel
  • 22,052
  • 14
  • 85
  • 185
Milan Jaros
  • 1,107
  • 17
  • 24
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
  • 494
  • 2
  • 4
1

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

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

For Java >= 1.8

Arrays.stream(array, incIndex, exclusiveIndex)
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];
}
Hsabes
  • 21
  • 3