Close

Java - How to get sub array in Java?

Java 

Followings are the different ways to work with sub array range:



Getting copy of sub array by using Arrays#copyOfRange

Arrays class defines multiple overloaded copyOfRange methods. In this example we are going to use this method:

int[] copyOfRange(int[] original, int from, int to)

package com.logicbig.example;

import java.util.Arrays;

public class ArrayRangeCopy {
public static void main (String[] args) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] ints1 = Arrays.copyOfRange(ints, 5, 10);
System.out.println(Arrays.toString(ints1));
}
}

Output

[6, 7, 8, 9, 10]


Getting copy of sub array by using System#arraycopy

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

package com.logicbig.example;

import java.util.Arrays;

public class ArrayRangeCopy2 {
public static void main (String[] args) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] newInts = new int[5];
System.arraycopy(ints, 5, newInts, 0, 5);
System.out.println(Arrays.toString(newInts));
}
}

Output

[6, 7, 8, 9, 10]


Working with sub array without copying

In some cases we don't want to copy large part of array over and over again. That's because copying large arrays may perform slow. There we should work on the same array instance instead of allocating new ones. We should use following patterns.


Working with sub array via callback

package com.logicbig.example;

import java.util.function.Consumer;

public class ArrayRangeConsumerExample {
public static void main (String[] args) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
arrayRange(ints, 5, 10, System.out::println);
}

public static void arrayRange (int[] ts,
int from, int to,
Consumer<Object> rangeConsumer) {
for (int i = from; i < to; i++) {
rangeConsumer.accept(ts[i]);
}
}
}

Output

6
7
8
9
10


Using methods which work on the sub array

JDK also has a lot of methods like these e.g. Arrays.binarySearch(), Arrays.fill(), java.io.Reader.read(chars, offset, len), java.io.Writer.write(chars, offset, len) etc

package com.logicbig.example;

public class MethodsWorkingWithSubArrayExample {
public static void main (String[] args) {
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
workWithRange(ints, 5, 10);
}

private static void workWithRange (int[] ints, int from, int to) {
for (int i = from; i < to; i++) {
System.out.println(ints[i]);
}
}
}

Output

6
7
8
9
10




See Also