Sobes.tech
Junior — Middle

How can you modify the contents of a collection during its traversal?

sobes.tech AI

Answer from AI

In Java, to safely modify a collection while iterating over it, it is recommended to use an iterator that supports removal or addition of elements.

Example using Iterator for removing elements:

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String item = iterator.next();
    if (item.equals("b")) {
        iterator.remove(); // safe removal of element during iteration
    }
}

To add elements during iteration, you can use ListIterator:

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
ListIterator<String> listIterator = list.listIterator();
while (listIterator.hasNext()) {
    String item = listIterator.next();
    if (item.equals("b")) {
        listIterator.add("d"); // adding element during iteration
    }
}

It is important not to modify the collection directly (for example, through list.remove()), as this will throw a ConcurrentModificationException.