Move current object to iterator to end of list

I have a problem with Java using an Iterator object (LinkedList.iterator ()). In the loop, I need to move the iterator object from somewhere to the end of the 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 cannot clone this.transitions for some reason. Is this possible, or do I really need to use the clone method?

Edit : I am currently doing this:

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

But the problem is only in this second line. I can’t add itens, this is me an internal iterator of the same object. :(

+3
source share
1 answer

You can save the second list of added items:

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);
+4
source

All Articles