It's not a secret anymore!
The moose likes Java in General and the fly likes ArrayList add method causing Memory Overrun Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "ArrayList add method causing Memory Overrun" Watch "ArrayList add method causing Memory Overrun" New topic

ArrayList add method causing Memory Overrun

Bill Riedl

Joined: Sep 08, 2009
Posts: 4
Hi I've been having this problem for a while. It seems that every time I try to use the add method on an ArrayList to insert an object into the list I get an error stating "out of memory...heap overrun". I would understand if these lists were large and the objects contained within then were complex but neither is the case. Here is the code snippet that causes the problem. Thanks in advance for any insight!

ResultObject ro = new ResultObject(str, distance);
if(res_.isEmpty()) res_.add //Places first object in the arrayList
for(int i =0; i<res_.size();i++) //walks through the arrayList
if(distance < res_.get(i).getDistance()) //This statement attempts to order the arrayList at time of entry by comparing the current result to the value in the arrayList
res_.add(i,ro) //This is the statement that causes the memory overrun!
added = true;
if(!added) //adds the object to the end of the list if it was not inserted above.
added = false;
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1789

Hi Bill!

1. try to remember to Use Code Tags. This helps people read your code.

2. Where do you declare your arraylist?

3. this line:

... is it meant to replace the item at index i, or do you want that item to go just before and push the item currently in i to the next slot?

4. this line:

.... doesn't add anything to the arraylist at all, do you realize that?

5. There is no way this code could compile; there are not enough semicolons. Try to Post Real Code.... it's more helpful when answering questions.

When you do things right, people won't be sure you've done anything at all.
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
Use TreeSet instead of ArrayList.
TreeSet automatically sorts items and checks if new item is already in the set,
and is more efficient than manually ordering of ArrayList.
With TreeSet your above code will simplify to only two lines:

The only thing you must do to use TreeSet is to implement equals() and compareTo() methods in your ResultObject class.

Danish Sualeh

Joined: Oct 06, 2005
Posts: 11

Can you paste the full stack trace?

Are you running the program from a command line or an IDE ?

There are certain parameters that can be passed to the JVM to control the allocated heap size
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46405
Doesn't sound like a "beginning" question any more. Moving thread.
I agree. Here's the link:
subject: ArrayList add method causing Memory Overrun
It's not a secret anymore!