best pattern for collections with remove-during-iteration?

edited January 2018 in JavaScript Mode

Hi there!

I'm updating some very old Processing cold - https://toys.alienbill.com/ - to run in browsers. Basically that means opening it in Processing 2, getting it to work there as Java, then switching to Processing.js (I haven't looked to make sure that Processing 3 still doesn't know Processing.js, but that's how it was a while back)

My biggest problem is with collections.

My old favorite was HashSet, which is no longer supported - but it made sense to me to say "I have a bunch of stuff I want to draw, I don't care what order". And then I would

HashSet<Thing> things = new HashSet<Thing>();
// ... add some things
// now loop:
Iterator<Thing> i = things.iterator();
while(i.hasNext){
   Thing t = i.next();
   t.move();
   if(t.isDead()){
        i.remove();
  }
}

So, the syntax was clunky, but the procedure was a little cleaner than my current practice of having an ArrayList just to store the things I want to remove, then removing them all at once...

ArrayList<Thing> things = new ArrayList<Thing>();
//...add some things
//now loop:
ArrayList<Thing> thingsToRemove = new ArrayList<Thing>();
for(Thing t : things){
  t.move();
  if(t.isDead()){
     thingsToRemove.add(t);
  }
}
things.removeAll(thingsToRemove);

(this because ArrayList's for() explodes if you try and remove while iterating over it)

So is there a cleaner way to remove something from a collection as you're iterating over that same collection? (In js, you can splice and what not if you iterate BACKWARDS from the end of an array... clearly a little hacky)

Answers

Sign In or Register to comment.