1

I want to implement an iterator for a circular linked list but i can't find how to imlement the ConcurrentModificationException when an user is trying to modify an iterator that is currently iterating.

I know i have to change the next and hasNext functions but i don't know how to do it.

I tried searching for java doc source code of iterator in order to help me understanding this but all i could find was "source code" with function names and documentation on how to use them ...

    public Iterator<Item> iterator() {
        return new ListIterator();
    }

    // an iterator, doesn't implement remove() since it's optional
    private class ListIterator implements Iterator<Item> {
        private Node current = last.next; //initialize as the first node
        public boolean hasNext(){
            return current == null;
        }
        public Item next(){
            if(hasNext() == false) throw new NoSuchElementException();
            Item item = current.item;
            current = current.next;
            return item;
        }
        public void remove(){
            throw new UnsupportedOperationException();
        }


    }
Lucien Ledune
  • 120
  • 11
  • 5
    most iterators and their collections use a property called `modCount`. If the collection gets updated the `modCount` gets increased by one. The iterator copies that `modCount` once when it is created and then checks every iteration that it still is the same as the one from the enclosing collection. `if(modCount != expectedModCount) throw ConcurrentModificationException()` – Lino Jan 10 '19 at 14:35
  • 2
    Agree with @Lino, you can see an example of that in ArrayList: http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/tip/src/share/classes/java/util/ArrayList.java – Zack Jan 10 '19 at 14:38
  • Hm, someone actively up-voting a duplicate. – J-Alex Jan 10 '19 at 14:42

0 Answers0