我测试了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);
}
}
答案 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();