Most efficient way to remove an object from inside a repeating ArrayList

I am trying to remove an object from iterating over ArrayList but cannot do it from within the loop, this is what I have at the moment

        for(Pearl pearl : this.pearls){
            pearl.onDraw(canvas);

            if(fish.isCollide(pearl)){
                this.pearls.remove(pearl);
            }
        }

      

The above code does not work if ArrayList is greater than 1.

I thought about changing the code to something like the following, but would rather know if there is an easier way.

       List<Pearl> pearls_delete = new ArrayList<Pearl>();


       for(Pearl pearl : this.pearls){
            pearl.onDraw(canvas);

            if(fish.isCollide(pearl)){
                pearls_delete.add(pearl);
            }
        }

        this.pearls.removeAll(pearls_delete);

      

+3


source to share


1 answer


Use Iterator

Iterator<Pearl> iter = this.pearls.iterator();
while ( iter.hasNext() ) {
   Pearl pearl = iter.next();
   // logic
   iter.remove();
} 

      



or simply

for (Iterator<Pearl> iter = pearls.iterator(); iter.hasNext();) {
   Pearl pearl = iter.next();
   // logic
   iter.remove();
} 

      

+9


source







All Articles