-2

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.

Anish
  • 89
  • 1
  • 10

1 Answers1

0

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();
    }
  }
}
Jeeppp
  • 1,553
  • 3
  • 17
  • 39