-8

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}]
3
  • 7
    Pardon me if I am asking an obvious question, but did you try debugging your code? arrr.length is always going to be greater than 0 (zero), hence your while loop never terminates. Commented Dec 9, 2024 at 13:14
  • If you are not familiar with using a debugger, you should learn. One of the key points on that page is Using a debugger is an expected basic skill. Commented Dec 9, 2024 at 17:46
  • perfect use case for the new Gatherers#windowFixed Gatherer available in Java 24 - javadoc Commented Dec 9, 2024 at 18:45

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

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.