我目前有迭代通過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