3

I'm having a problem on Java using Iterator (LinkedList.iterator()) object. In a looping, I need move a iterator object from some place to end of list.

For instance:

final Iterator<Transition> it = this.transitions.iterator();
while(it.hasNext()) {
    final Transition object = it.next();

    if(object.id == 3){
        // Move to end of this.transitions list
        // without throw ConcurrentModificationException
    }
}

I can't clone this.transitions for some reasons. It's possible, or I really need use the clone method?

Edit: currently, I do it:

        it.remove();
        this.transitions.add(object);

But the problem is just on this second line. I can't add itens, it I'm inner an iterator of the same object. :(

David Rodrigues
  • 12,041
  • 16
  • 62
  • 90
  • Have you tried it? I'm pretty sure you can modify `this.transitions` without any problems because you're not looping on it directly, you're using an `Iterator`, which is basically a clone of `this.transitions`. – Jonah May 22 '11 at 00:50
  • Yeah. `it.remove()` works perfectly on remotion. But the problem is add to end of list by use `this.transitions.add(object)` method. – David Rodrigues May 22 '11 at 00:52
  • Oh, you mean when you add it at the end it doesn't come up in the `Iterator`? – Jonah May 22 '11 at 00:54
  • When I add on end of list it throw the `ConcurrentModificationException`, because the `this.transition` is "locked" for modifications. – David Rodrigues May 22 '11 at 00:58
  • @jonah no he means that the fail-fast behavior of the iterator is stopping him from doing what he wants – ratchet freak May 22 '11 at 00:59

1 Answers1

6

you can keep a second list of elements to be added:

final Iterator<Transition> it = this.transitions.iterator();
final List<Transition> tmp = new ArrayList();//using a list will keep the order
while(it.hasNext()) {
    final Transition object = it.next();

    if(object.id == 3){
        it.remove();
        tmp.add(object);
    }
}
this.transitions.addAll(tmp);
ratchet freak
  • 47,288
  • 5
  • 68
  • 106
  • Yeah. It is the unique way that I think too. I'll accept you answer in a minute. If exists other way (without make a new variable or clone) will be welcome. But only for work already better than before. hehe thanks – David Rodrigues May 22 '11 at 01:00