Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nullify object that is part of ArrayList java

I have an array list:

private ArrayList<PerfStatBean> statFilterResults;

I want to iterate through it like:

Iterator<PerfStatBean> statsIterator = statFilterResults.iterator();
while(statsIterator.hasNext()){
  i++;
  PerfStatBean perfBean = statsIterator.next();
  .........

I would like to delete the bean from statFilterResults after I run through it inside the while loop to free up memory. I believe if I do something like

 perfBean = null;

it won't do the job as the perfBean reference will be null but the object will still be in memory.

Any ideas?

Thanks,

Tam

like image 668
Tam Avatar asked Dec 09 '25 15:12

Tam


1 Answers

This probably isn't a great optimisation. If the memory requirements are large, then you probably don't want to store them all in a list in the first place - process the objects as they are created.

However, taking the question literally, ListIterator.set is the method for you.

for (
    ListIterator<PerfStatBean> iter = statFilterResults.listIterator();
    iter.hasNext()
) {
    ++i;
    PerfStatBean perfBean = iter.next();
    iter.set(null);
    ...
}
like image 184
Tom Hawtin - tackline Avatar answered Dec 12 '25 03:12

Tom Hawtin - tackline



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!