开发者

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() 开发者_C百科- 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);


From the Java API docs:

The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling [Iterator.remove].

So it's loopy loop for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜