我目前有迭代通过ArrayList的问题。我在这里看过几篇文章,但似乎没有解决我的问题。这里是我的代码:ConcurrentModificationException迭代通过Arraylist(不删除)
//restaurants contains a list of all restaurants and i want to filter them
List<Restaurant> newList = new ArrayList<Restaurant>();
List<Restaurant> allRestaurants = new ArrayList<Restaurant>(restaurants);
if (query != null && query.length() > 0 && !query.equals("*")) {
synchronized (allRestaurants) {
for (Iterator<Restaurant> it = allRestaurants.iterator(); it
.hasNext();) {
Restaurant restaurant = it.next();
if (restaurant.getCity().contains(query)) {
synchronized (newList) {
newList.add(restaurant);
}
} else {
newList = allRestaurants;
}
}
}
这是代码是由我修改与一些想法,我已经在这里读(同步,使用迭代器代替的for-each循环)。我甚至已经对整个方法进行了同步,但仍然得到一个异常。
唯一的例外是发生在下面一行:
Restaurant restaurant = it.next();
,我不明白。我不会操纵这一行中的列表。为什么会发生这种情况,我该如何解决这个问题?
你可能不想有一个嵌套的同步块 – 2013-03-13 20:29:01