WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Collections Β· Expert Β· question 80 of 100

How does the iterator() method work in Java Collections, and how can you modify the collection while iterating over it in a thread-safe way?

πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

The iterator() method is used to create an iterator over the elements of a collection in Java. The Iterator interface provides methods for traversing and modifying the elements of a collection, including next(), hasNext(), and remove().

The Iterator interface is fail-fast, which means that if the collection is modified while an iterator is iterating over it, a ConcurrentModificationException will be thrown. This is because the iterator maintains an internal count of the number of modifications made to the collection, and if the count changes unexpectedly, it assumes that the collection has been modified and throws an exception.

To avoid the ConcurrentModificationException, one solution is to use a thread-safe collection class such as ConcurrentHashMap or CopyOnWriteArrayList. These collections are designed to be safe for concurrent access by multiple threads, and they provide iterators that can be safely used to traverse and modify the collection.

Another solution is to use a synchronized block to lock the collection while it is being modified. This ensures that only one thread can modify the collection at a time, which prevents concurrent modification exceptions from occurring. Here is an example of using a synchronized block to safely modify a collection while iterating over it:

List<String> list = new ArrayList<>();
// add elements to the list
Iterator<String> iterator = list.iterator();
synchronized(list) {
    while (iterator.hasNext()) {
        String element = iterator.next();
        // modify the element or remove it
    }
}

In this example, the synchronized block locks the list while the iterator is being used, which prevents other threads from modifying the list at the same time. This ensures that the iterator will not encounter any unexpected modifications and will not throw a ConcurrentModificationException.

It’s important to note that modifying a collection while iterating over it can cause unexpected behavior and should be avoided if possible. However, if it is necessary to modify the collection while iterating over it, the above solutions can help prevent concurrent modification exceptions and ensure thread safety.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview β€” then scores it.
πŸ“ž Practice Java Collections β€” free 15 min
πŸ“• Buy this interview preparation book: 100 Java Collections questions & answers β€” PDF + EPUB for $5

All 100 Java Collections questions Β· All topics