Collections


Iterable and Iterators

  • Items cannot be added to a collection directly while iterating through the collection in a for-each loop or through the collection’s iterator; doing so will throw a ConcurrentModificationException at runtime. The appropriate way to modify the structure of a collection that is undergoing iteration is through the iterator.remove() method.

  • // Reference Collections1 p. 174

    // throws ConcurrentModificationException
    for (Task t : tuesdayTasks) {
    if (t instanceof PhoneTask) {
    tuesdayTasks.remove(t);
    }
    }
    // throws ConcurrentModificationException
    for (Iterator it = tuesdayTasks.iterator() ; it.hasNext() ; ) {
    Task t = it.next();
    if (t instanceof PhoneTask) {
    tuesdayTasks.remove(t);
    }
    }
    for (Iterator it = tuesdayTasks.iterator() ; it.hasNext() ; ) {
    Task t = it.next();
    if (t instanceof PhoneTask) {
    it.remove();
    }
    }


    Synchronized Collections


    java.util.Collections class


    References
    Collections1: Java Generics and Collections. Maurice Naftalin and Philip Wadler. O’Reilly Media 2007.

    You must be logged in to post a comment.