I was trying to implement a doubly linked list in java and I am overriding the default Iterator interface , But how can I check for concurrent modification error inside my overridden Iterator?
@Override
public Iterator<T> iterator(){
return new Iterator<T>() {
private Node<T> trav = head;
@Override
public boolean hasNext() {
return trav!=null;
}
@Override
public T next() {
T data = trav.data;
trav = trav.next;
return data;
}
};
}
This is my overridden Iterator interface.
When implementing a custom iterator for a Linked List in Java, you can check for concurrent modification errors by using the
modCountfield of theAbstractListclass, which is the parent class of theLinkedListclass. This field tracks the number of structural modifications (additions, deletions, etc.) that have been made to the list. You can compare the value ofmodCountbefore and after iterating through the list to determine if any modifications have been made, and throw aConcurrentModificationExceptionif the values are different. Here is an example: