Annul an object that is part of an ArrayList

I have a list of arrays:

private ArrayList<PerfStatBean> statFilterResults;

I want to iterate it like this:

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

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

 perfBean = null;

it will not do the job, since the perfBean reference will be null, but the object will still be in memory.

Any ideas?

Thanks,

There

+3
source share
9 answers

This is probably not a big optimization. If the memory requirements are large, then you probably do not want to store them all in the list in the first place - process objects as they are created.

, , ListIterator.set - .

for (
    ListIterator<PerfStatBean> iter = statFilterResults.listIterator();
    iter.hasNext()
) {
    ++i;
    PerfStatBean perfBean = iter.next();
    iter.set(null);
    ...
}
+3
+2

?

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

statFilterResults.clear();
+2

, , .

statFilterResults.removeAll(beansToDelete);

, , , - , .. - foreach . :

for (PerfStatBean bean : statFilterResults) {
    ...
}
+1
ListIterator<PerfStatBean> statsIterator = statFilterResults.iterator();
while(statsIterator.hasNext()){
  i++;
  PerfStatBean perfBean = statsIterator.next();
  ...
  statsIterator.remove();
}
+1
while(statsIterator.hasNext()){
  i++;
  PerfStatBean perfBean = statsIterator.next();
  statsIterator.remove();
+1

java . , , , (GC , ). , , Runtime.getRuntime(). Gc()

0

, , ...

API:

finalize() ", , , ".

" , finalize , , Java , , , , , , ".

, , bean , . , ArrayList bean ( , remove() ).

0

... bean statFilterResults , while, .

arraylist, null , , java ( )

, - :

this.bean = new PerfStatBean();

....

arrayList.add( this.bean );

, gc'ed.

, ..

 arrayList.add( new PerfStatBean() );

:

while(....){
    .... 
}

arrayList.clear();

gc.

: "" , , :

while(....){
    .... 
}

arrayList.clear();

.

0

Source: https://habr.com/ru/post/1712518/


All Articles