farm ostrich
farm ostrich

Reputation: 5959

Java concurrency iterator arraylist shenanigans

I have some code that uses an iterator to traverse an arraylist. If a certain condition is met, I want to add an object to the arraylist. Can this be done with an iterator? Or do I need to just use a loopedy loop?


itr=particleArr.iterator();
while (itr.hasNext()){
    particle=itr.next();
    if (isMyLifeUtterlyMeaningless)) {
         particleArr.add(new Particle(particle.getXCoor() - 5,
             particle.getYCoor() + 5,
             colorState));
}}
which throw a modification exception. So how do I rewrite this with the iterator?

Upvotes: 1

Views: 438

Answers (2)

clstrfsck
clstrfsck

Reputation: 14829

How about:

    newParticles = new ArrayList<Particle>();
    for (Particle particle : particleArr) {
        if (isMyLifeUtterlyMeaningless)) {
            newParticles.add(new Particle(particle.getXCoor() - 5,
                                          particle.getYCoor() + 5,
                                          colorState));
        }
    }
    particleArr.addAll(newParticles);

Upvotes: 4

Related Questions