Why does it.next() throw java.util.ConcurrentModificationException?

前端 未结 3 1980
情书的邮戳
情书的邮戳 2020-12-29 13:00
final Multimap terms = getTerms(bq);
        for (Term t : terms.keySet()) {
            Collection C = new HashSet(t         


        
3条回答
  •  我在风中等你
    2020-12-29 13:59

    The reason is that you are trying to modify the collection outside iterator.

    How it works :

    When you create an iterator the collection maintains a modificationNum-variable for both the collection and the iterator independently. 1. The variable for collection is being incremented for each change made to the collection and and iterator. 2. The variable for iterator is being incremented for each change made to the iterator.

    So when you call it.remove() through iterator that increases the value of both the modification-number-variable by 1.

    But again when you call collection.remove() on collection directly, that increments only the value of the modification-numbervariable for the collection, but not the variable for the iterator.

    And rule is : whenever the modification-number value for the iterator does not match with the original collection modification-number value, it gives ConcurrentModificationException.

提交回复
热议问题