David Rodrigues
David Rodrigues

Reputation: 12532

Move current object on iterator to end of list

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. :(

Upvotes: 3

Views: 2710

Answers (1)

ratchet freak
ratchet freak

Reputation: 48196

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

Upvotes: 6

Related Questions