Search code examples
javaarraylistout-of-memoryjava-streamtoarray

java.lang.OutOfMemoryError: Java heap space on stream.mapToInt()/ArrayLists


ArrayList<Integer> digitList = new ArrayList<Integer>();
ArrayList<Integer> newBase = new ArrayList<Integer>();

public void toX(int base, int oNum) {
    while(base > 0) {
        digitList.add(base % 10);
        base /= 10;
    }
    int[] digits = digitList.stream().mapToInt(i->i).toArray();
    for(int i = 0; i<digits.length/2; i++) {
        int a = digits[i];
        digits[i] = digits[digits.length -i -1];
        digits[digits.length -i -1] = a;
    }
    System.out.println(Arrays.toString(digits));
    for(int i = 0; i < digits.length; i++) {
        total += digits[i];
    }
    System.out.println(total);
    while(total >= 0) {
        if(total >= oNum) { 
        newBase.add(total - oNum);
        total -= oNum;
        System.out.println(total);
        }
        else {
            newBase.add(total);
        }
    }
    int[] ans = newBase.stream().mapToInt(i->i).toArray();
    System.out.println(Arrays.toString(ans));
}

This method is meant to convert a number in base 10 to a number in baseX. Its unfinished, and i keep getting multiple errors:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.Arrays.copyOf(Unknown Source)
    at java.util.ArrayList.grow(Unknown Source)
    at java.util.ArrayList.ensureExplicitCapacity(Unknown Source)
    at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
    at java.util.ArrayList.add(Unknown Source)
    at BaseConverter.toX(BaseConverter.java:34)

line 33-35 is:

else {
    newBase.add();
}

I THINK that the problem is coming from the stream, but I am very inexperienced with stream and arraylists.


Solution

  • while(total >= 0) {
        if(total >= oNum) { 
            newBase.add(total - oNum);
            total -= oNum;
            System.out.println(total);
        }
        else {
            newBase.add(total);
        }
    }
    

    If you hit the else branch it'll keep adding items to newBase without changing total, leading to an infinite loop.