我目前在遍历 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-loop)。我什至同步了整个方法,但仍然出现异常。
异常发生在以下行:
Restaurant restaurant = it.next();
我不明白。我没有在这一行中操纵列表。为什么会发生这种情况,我该如何解决?
最佳答案
else{
newList = allRestaurants;
}
这几乎肯定是您的问题。
将 newList
分配给 allRestaurants
然后添加到 newList
会导致您的共修改。
在 newList = allRestaurants
之后,任何添加到 newList
的内容都会更新 allRestaurants
中的 mod 计数,从而更新您的错误。
关于java - 遍历 Arraylist 时出现 ConcurrentModificationException(不删除),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15395732/