berney_mark
berney_mark

Reputation: 53

Why is this exception outputting from my Iterator search?

I am receiving an ConcurrentModificationException when trying to use Iterator to search for a specific Integer.

I don't know why it's there. Any research I've looked into says it's an exception that appears when I try to edit the list inside a for loop. I am not doing that, in fact I'm not even editing the list in the Iterator.

private ArrayList<Integer> list = new ArrayList();
private ListIterator<Integer> iterator = list.listIterator();

public void search(int input) {
    while (iterator.hasNext()) {
        if (input == iterator.next()) {
            System.out.println(iterator.next());
       }
    } 
}

public static void main(String[] args) {
    SearchList sl = new SearchList();

    for (int i = 0; i < 10; i++) {
        sl.list.add(i);
    }

    System.out.println(sl.list);

    sl.search(6);
}

EXPECTED OUTPUT:

6

ACTUAL OUTPUT:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
    at java.util.ArrayList$Itr.next(ArrayList.java:859)
    at SearchList.search(SearchList.java:23)
    at SearchList.main(SearchList.java:38)```

Upvotes: 1

Views: 64

Answers (2)

IfOnly
IfOnly

Reputation: 540

The issue here is that you created an iterator at the start, then modified the list.

Solution: In the search method get the iterator and work on it.

Upvotes: 3

Robert Kock
Robert Kock

Reputation: 6018

You create the iterator (when initializing the class instance) and after that you modify the underlying list.
The iterator doesn't like that.

As the javadoc says:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Upvotes: 4

Related Questions