为什么以下代码使用Iterator next()和remove()抛出ConcurrentModificationException?

时间:2016-08-05 08:24:17

标签: java iterator

我测试了next()接口的remove()Iterator方法。我得到以下例外:

  

线程“main”中的异常java.util.ConcurrentModificationException

这是我的代码:

import java.util.*;

public class ListTest {
    public static void main(String[] args) {
        Collection<Integer> list = new ArrayList<Integer>();
        Iterator<Integer> iterator = list.iterator();

        Collections.addAll(list, 1, 2, 3, 4, 5);
        if (iterator.hasNext()) {
            iterator.next();
            iterator.remove();
        }

        System.out.println(list);
    }
}

2 个答案:

答案 0 :(得分:6)

使用Iterator next()remove()时没有问题。

ConcurrentModificationException是在List创建Iterator后向List添加元素造成的。{/ 1}

您应该在创建Iterator之前向Iterator<Integer> iterator = list.iterator(); Collections.addAll(list, 1, 2, 3, 4, 5); 添加元素。

变化:

Collections.addAll(list, 1, 2, 3, 4, 5);
Iterator<Integer> iterator = list.iterator();

为:

<?php get_header(); ?>
    <div class="container">
        <div class="row">
            <?php get_template_part( 'include-cat-tag' ); ?>
            <div class="col-xs-12 col-sm-9 col-md-9 list-page-middle">
                <header class="clearfix">
                    <h1><?php single_cat_title( '', true ); ?></h1>
                </header>
                <?php
                    wp_reset_query();
                    $categories = get_the_category();
                    $category_id = $categories[0]->cat_ID;
                    $args = array(
                        'posts_per_page' => 100,
                        'category__in' => array($category_id),
                        'orderby' => 'meta_value title',
                        'order' => 'ASC',
                        'post_status' => 'publish',
                        'meta_key' => 'betyg',
                        'child_of' => $category_id
                    );
                    query_posts( $args );
                    if (have_posts()): while (have_posts()) : the_post();
                    get_template_part( 'include-list-post' );
                ?>
                <?php endwhile; ?>
                <?php else: ?>
                    <?php get_template_part( 'include-no-post' ); ?>
                <?php endif; ?>
            </div>       
        </div>
        <?php 
            get_template_part( 'include-list' );
            get_template_part( 'include-social' );
        ?>
        </div>
    </div>
    <?php get_footer(); ?>

并且您的循环将正常工作。

答案 1 :(得分:4)

您得到此异常是因为您在创建迭代器后通过添加元素来修改List的状态,因此当您在迭代器上调用next()时,它会在内部检查基础List }已被修改,如果是这样,它会引发ConcurrentModificationException,这就是这里的情况。

尝试按顺序颠倒顺序:

Collections.addAll(list, 1, 2, 3, 4, 5);
Iterator<Integer> iterator = list.iterator();