Skip to content
Advertisement

Java heap space error while creating ArrayList of large number of objects?

I have created an ArrayList (Java) of my custom class objects with a size around 3000. But when I run my code it gets the error “Heap space error”.

I want to keep thousands of objects in an ArrayList at runtime without getting out of heap space.

How can the heap space error be avoided?

Advertisement

Answer

It seems like you need to pass your program more memory.

Try running it like this:

java -Xmx256M MyApp

-Xmx sets the maximum heap size for Java. Putting M afterwards means megabytes, and G afterwards means gigabytes. So you can always do this if you have a bunch of memory:

java -Xmx1g MyApp
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement