Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConcurrentModificationException while iterating through Arraylist (not removing)

I currently have a problem with iterating through an ArrayList. I've read several posts here, but nothing seem to have resolved my problem. Here is my code:

//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;
                    }
                }
            }

This is code was modified by me with several ideas i've read here (synchronized, using iterator instead of for-each-loop). I even have synchronized the whole method and still get an exception.

The exception is happening in following line:

Restaurant restaurant = it.next();

which I don't understand. I am not manipulating the list in this line. Why is this happening and how can i fix it?

like image 861
MrHill Avatar asked Jul 02 '26 02:07

MrHill


1 Answers

else{
    newList = allRestaurants;
}

That is almost certainly your issue.

Assigning newList to allRestaurants then adding to newList is causing your comodification.

That is after newList = allRestaurants any add to newList will update the mod count in allRestaurants and thus your error.

like image 135
John Vint Avatar answered Jul 04 '26 18:07

John Vint