S
S
Skoleev2021-10-26 22:06:57
Java
Skoleev, 2021-10-26 22:06:57

Why doesn't ConcurrentModificationException occur during collection modification by remove() method on LinkedList?

Deque<Employee> employeeDeque = new LinkedList<>();
        employeeDeque.offerLast(new Employee("Michael", 250));
        employeeDeque.offerLast(new Employee("John", 250));
            Iterator iterator = employeeDeque.iterator();
        while (iterator.hasNext()) {
            iterator.next();
            employeeDeque.remove(new Employee("Michael", 250));
    }


The same code with ArrayList will throw an error, but remove() on LinkedList during iteration does not cause it.
When changing the collection using Add() and Offer(), ConcurrentModificationException is thrown immediately.
Why is remove() so special when dealing with LinkedList?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-10-27
@xez

You have a special case for two elements.
ConcurrentModificationException throws iterator.next();
Everything is OK in the first pass, until one element is deleted, and you don’t have a second pass in the loop, because your two element collection ends (iterator.hasNext() == false)
Add third element - get ConcurrentModificationException

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question