Dynamically remove items from a list

I have a problem with deleting list items when repeating through a list. The code:

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

I get ConcurrentModificationExceptionone that I fully understand. I remove an item from the list while in a loop that goes through the list. Intuitively, this would trigger a loop index.

My question is: how else should I remove items that are not enabledor selectedfrom this list?

+5
source share
4 answers

The easiest way to remove items from a list in a loop is to use ListIteratorand remove items using the procedureiterator.remove()

+8
source

, , undefined. :

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

. .

+6

. , , , remove(), Iterable<E>.

: Javadoc, nevermore ( ):

void remove()

, ( ).

, , .

List<E> removed = new ArrayList<E>();
for(E element : list) {
    if(someCondition) removed.add(element);
}
list.removeAll(removed);

, , , remove.

+3

ConcurrentModificationException , Iterator.

"fail-fast", , , , , , . .

@Claudiu , . , , Iterator.

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

All Articles