简体   繁体   中英

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 l oopedy 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM