The wrong way

for (Object obj : list) {
    if (condition is true) {
        list.remove(obj);
    }
}

This will result in

Exception in thread "main" java.util.ConcurrentModificationException

The correct (or safe) way

for (Iterator<Object> itr = list.iterator(); itr.hasNext();) {
    Object obj = itr.next();

    if (condition is true) {
        itr.remove();
    }
}

Reference



Published

31 October 2014

Tags


Table of Contents