I want to split an array of integers into multiple subArrays of size n.How can this be achieved?
I tried using following way but it gives OutOfMemoryError
import java.util.*;
public class SplittingArraysIntoSubArrays {
public static void main(String[] args) {
int[] arrr = {1,3,2,5,4,6,8,13};
List<int[]> arrayList = new ArrayList<>();
int arrayLength = arrr.length;
int n =3;
int counter=1;
while(n*counter<arrayLength) {
arrayList.add(Arrays.copyOf(arrr, 3));
counter++;
}
System.out.println("Done");
}
}
Below is the output i get
[{1,3,2},{1,3,2}]
>Solution :
You need to keep track of your position in the array arrr. You also need to check that there are 3 elements when you copy the (up to) three elements into a new array. And you need to copy ranges of elements from the array, so Arrays.copyOfRange(int[], int, int) would be more appropriate. Putting that together might look something like,
int[] arrr = { 1, 3, 2, 5, 4, 6, 8, 13 };
List<int[]> arrayList = new ArrayList<>();
for (int i = 0; i < arrr.length; i += 3) {
int n = Math.min(3, arrr.length - i);
arrayList.add(Arrays.copyOfRange(arrr, i, i + n));
}
for (int[] arr : arrayList) {
System.out.println(Arrays.toString(arr));
}
System.out.println("Done");
Which outputs
[1, 3, 2]
[5, 4, 6]
[8, 13]
Done