Frage

I am throwing a ConcurrentModificationExample in the following code. I checked the API and it has to do with me trying to modify an object while another thread is iterating over it. I am clueless on the matter. I have created a comment above the line causing the exception. The Employee class doesn't contain anything other than the three variables for storing information.

I will be including the entire class as I would also like to know if there is a way to simplify my code as it repeats many things such as object creation and adding everything to the lists.

War es hilfreich?

Lösung

When you call employeesByAge in here with dep.employees:

dep.employeesByAge(dep.employees)

that will pass in dep.employees to employeesByAge such that in:

public class Department{
    LinkedList<Employee> employees = ...;
    public LinkedList<Employee> employeesByAge(LinkedList<Employee> outputList) {
        ...
    }
}

both the employee member field and the outputList parameter refers to the same list, not just two list with the same content, but the same list instance.

Then you do:

for (Employee emp: employees){
    //the list is null. add the first employee

    if (outputList.isEmpty()){
        outputList.add(emp);
    } else
    ...
}

which iterates the employee and modifies outputList, but remember that these two are the same list object. Thus, ConcurrentModificationException.

Andere Tipps

What you're attempting to do is similar to this...

List list = ...;
for(item: list) {
    list.add(item);
}

That is, you're updating a collection with elements by iterating over the same collection. All

outputList.add(...);

in Department are adding elements to the collection from the same collection 'employees'. In main(), by doing

dep.employeesByAge(dep.employees)

you're attempting to update 'dep.employees' with 'dep.employees.' which results in concurrent modification exception.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top