1

I have a Country class which keeps a list that consisted of Human objects. And in Country class I have following function;

public void processOneDay(int day, List<Country> countryList, int numberOfCountries ){
        ListIterator<Human> iter = people.listIterator();
        while(iter.hasNext()){
            Human h = iter.next();
            h.move(day, countryList, numberOfCountries);
        }
    }

The move() method of Human class is responsible for movement of a Human from one country to other but this method is removing that person from source country's person list and add it to destination country's people list. So, doing this operation while iterating causes me ConcurrentModificationException. I tried to use remove function of iterator itself but I messed up things more.So, how can I handle this situation?

2 Answers 2

2

Just make a copy of the list, you can use this one for iterating.

List<Human> copy = new ArrayList<Human>(people);

Sign up to request clarification or add additional context in comments.

Comments

0

As you discovered, you can't modify a list that you are iterating, so there are two choices, either you need to iterate over a copy of the list, or you need to traverse the list using a for loop that and directly index the items in the list.

Copying the list is much easier to write, but if the list is very big you will waste lots of CPU cycles and memory. Using for (var i = 0; i < list.Count; i++) list[i] is a bit more complicated but much more efficient. Note that if you remove items from the list then you need to not increment i.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.