When implementing a custom iterator for a Linked List in Java, you can check for concurrent modification errors by using the modCount
field of the AbstractList
class, which is the parent class of the LinkedList
class. This field tracks the number of structural modifications (additions, deletions, etc.) that have been made to the list. You can compare the value of modCount
before and after iterating through the list to determine if any modifications have been made, and throw a ConcurrentModificationException
if the values are different. Here is an example:
public class MyLinkedListIterator<E> implements Iterator<E> {
private final MyLinkedList<E> list;
private int expectedModCount;
private Node<E> current;
public MyLinkedListIterator(MyLinkedList<E> list) {
this.list = list;
this.expectedModCount = list.modCount;
this.current = list.first;
}
@Override
public boolean hasNext() {
return current != null;
}
@Override
public E next() {
checkForConcurrentModification();
E element = current.element;
current = current.next;
return element;
}
@Override
public void remove() {
checkForConcurrentModification();
// implementation of remove() method goes here
}
private void checkForConcurrentModification() {
if (list.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
}
}