Tag Archives: Foreach Loop Remove/add Element Error

JAVA: How to Solve Foreach Loop Remove/add Element Error

In fact, the reason for reporting an error is to throw an exception, which violates the fail fast protection mechanism

At this point, we replace the iterator to implement the loop

List<String> list=new ArrayList<>();
list.add("1");
list.add("2");
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
    String item=iterator.next();
    if(Conditions for deleting elements){
        iterator.remove();
    }    
}


Exception Writing
for(String item:list){
    if(Conditions){
        list.remove(item);
    }
}