Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically removing elements from List

Tags:

java

arraylist

I am having an issue removing elements of a list while iterating through the list. Code:

For (WebElement element: list){
    if (!element.isEnabled() || !element.isSelected()){
        list.remove(element);
    }
}

I get a ConcurrentModificationException, which I totally understand. I am removing an item from a list while in the loop that goes through the list. Intuitively, that would screw up the indexing of the loop.

My question is, how else should I remove elements that are either not enabled or selected from this list?

like image 468
jamesfzhang Avatar asked Nov 18 '11 21:11

jamesfzhang


2 Answers

The easiest way to remove elements from a list in a loop is to use an ListIterator and remove elements using the routine iterator.remove()

like image 130
Johan Sjöberg Avatar answered Oct 04 '22 21:10

Johan Sjöberg


Modifying a list while iterating through it, in a way outside of using the iterator, results in undefined behavior. You'll have to use an iterator explicitly:

Iterator<WebElement> iter = list.iterator();
while (iter.hasNext()) {
    WebElement element = iter.next();
    if (!element.isEnabled() || !element.isSelected()) {
        iter.remove();
    }
}

See this question for more.

like image 45
Claudiu Avatar answered Oct 04 '22 22:10

Claudiu