简体   繁体   中英

Deleting Part of An Array in Java to Free Memory on Heap

I am implementing a dynamic programming algorithm for the knapsack problem in Java. I declare the array and then initialize its size to be [number of objects][capacity of knapsack].

When my number of objects or my capacity gets too large, I get a memory error because I run out of space on the heap. My questions is: If I delete rows from my double array as I go along, will Java free the memory as I delete? Or does Java reserve that memory space for the size of the array I originally created? If it's the latter, is there a way to manually free the memory in Java?

Thanks for your Help!

The short answer is "yes" - if you're using arrays like this:

private void foo () {
  int[][] bar = new int[10][10];
  bar[1] = null;  
  //at this point, the array that was in bar[1] is eligible for garbage collection
  //unless someone else has a reference to it
}

It should free the memory a bit later, not necessarily as you remove the rows. It will however reuse that memory for new data.

Probably you're running with to little ram, try increasing it using:

java -Xmx128m you.app.Main

That will run your app with 128 mb of RAM.

Yes it works. Java does not have multidimensional arrays but only jagged arrays (arrays of arrays). So the first array is basically only an array of pointers to the real arrays of contents.

That has the positive effect than whenever you assign a new array to one of the jagged areas the old one can be garbage collected. (see Sbodd answer for an example)

无法从数组的一部分中释放内存...因为在Java中,您无法从数组中删除元素..相反,您可以横穿该数组并存储到所需大小的另一个数组中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM