Search code examples
javalistrecursionjava.util.concurrent

Deletenig an element from a list while it's being iterated recursively throws exception


I have the following code:

private void deletePersonFromList(String dni, ObservableList<Persona> persons){
    for(Persona p : persons){
        if(p.getChildren().isEmpty()) {
            if(p.getDNI().equals(dni)) {
                persons.remove(p);
            }
        } else deletePersonFromList(dni, p.getChildren());
    }
}

What i'm trying to do, is delete an element in a list if it matches a condition, this is done recursively because said elements can contain a list of elements themselves.

Doing this throws java.util.ConcurrentModificationException because the list is being iterated. What approach can help me do this?

This is an issue i'm facing while working on a school assignement, so please don't answer with just code solving it(if posible), i'd like to understand what should I do in this cases and why.

Thanks in advance!


Solution

  • You should use Iterator instead of foreach:

       public static void main(String[] args) throws Exception {
            final List<String> list = new ArrayList<>(of("a", "b", "c"));
            final Iterator<String> iterator = list.iterator();
    
            while (iterator.hasNext()) {
                final String value = iterator.next();
                iterator.remove();
                System.out.println("List: " + list + "\tRemoved: " + value);
            }
        }