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?
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With