How do i resolve 'concurrentmodificationexception in java'?

Example:

List list = new ArrayList<>();
list.add(1);
for(Integer i : list) {
    list.remove(i);
}
Solution:

The error arises from modifying a collection directly while iterating over it. To avoid it, use an Iterator's remove method or modify after iteration.


List list = new ArrayList<>();
list.add(1);
Iterator it = list.iterator();
while(it.hasNext()) {
    Integer i = it.next();
    it.remove();
}

Beginner's Guide to Java