An error will be reported when deleting the list collection foreach in java

When using the foreach loop of the List collection in Java to traverse elements, elements cannot be deleted within the loop body, otherwise a ConcurrentModificationException will be thrown.

This is because when using a foreach loop, Java uses an iterator to traverse the elements in the collection, and when the collection is modified, the iterator may become invalid, causing a ConcurrentModificationException exception to be thrown.

In order to avoid this problem, you can use the remove() method of Iterator to delete elements, which can avoid the occurrence of ConcurrentModificationException. For example:

List<String> list = new ArrayList<>();
// 添加元素
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    
    
    String item = iterator.next();
    if (shouldRemove(item)) {
    
    
        iterator.remove(); // 使用Iterator的remove()方法删除元素
    }
}

In this example, we use an Iterator to iterate over the elements in the collection and use the remove() method to delete elements. This can avoid ConcurrentModificationException exceptions that occur when using foreach loops.

Guess you like

Origin blog.csdn.net/Fine_Cui/article/details/129027442