• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList add method causing Memory Overrun

 
Bill Riedl
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
else
{
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.
{
res_.add(ro)
added = false;
}
}
 
Janeice DelVecchio
Saloon Keeper
Posts: 1809
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ireneusz Kordal
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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
Sheriff
Pie
Posts: 50168
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doesn't sound like a "beginning" question any more. Moving thread.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic