How do I fix "Java Heap Error"?

So I’m trying to make a program that sorts 10 numbers, and I wanted to used an ArrayList. However, whenever I run my program it gives me the error: java.lang.OutOfMemoryError: Java heap space, and I can’t figure out why. I’ve tried looking up causes, but none seemed to work. I’d like to understand why this error is happening so it doesn’t happen in the future when programming the robot.

Here is the code, thank you in advance for any help

import java.util.*;

public class SortNumbers
{
  public static void main(String args[]){

      //Creating the neccassary Objects
      Scanner scan = new Scanner(System.in);
      ArrayList<Integer> numbers = new ArrayList<Integer>();
      int input;
      
      //Ask the user to input 10 numbers
      System.out.println("Please enter 10 integers");
      
      //Enter the numbers and sort them into the array
      input = scan.nextInt();
      numbers.add((Integer) input);
      
      for(int i = 0; i < 10; i++){
          input = scan.nextInt();

          //Sort the numbers immediatly into the ArrayList
          for(int j = 0; j < numbers.size(); j++){
              //If the number is lest the current index, inset the number at that index
              if(input < numbers.get(j).intValue()) numbers.add(j, (Integer) input);
            }
          //If the number is greater than the last element, add it to the end of the list
          if(input > numbers.get(numbers.size()-1).intValue()) numbers.add((Integer) input);
          
        }
      
      //Print out the sorted array
      System.out.println("The numbers in sorted order: ");
      for(Integer num : numbers) System.out.println(num);
      
    }
}

This code seems suspect, as you’re adding to the list while you’re iterating over it, e.g. numbers.size() will grow when you call numbers.add(). Did you mean to stop iterating when you added the number?

I definitely recommend using a debugger to step through your code to validate its operation.

Thank you, you were right. It turned out to be because I was dynamically changing the size. I fixed the problem by adding a break after adding the number like so:

for(int j = 0; j < numbers.size(); j++){
   //If the number is lest the current index, inset the number at that index
   if(input < numbers.get(j).intValue()){
      numbers.add(j, (Integer) input);
      break;
   }
}

Thank you for help!

Since you seems to understand how does sorting works (in ascending order), you can use Collection.sort(arrayList) to sort your arrayList much quicker in the future, instead of writing the entire sorting algorithm again.

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.