0
votes

My graph keeps a set of vertices, and each Vertex has number, a list of it's adjacent vertices, and indicator if it's visited or not. My code has to reverse an edge of graph but it throws CurrentModificationException. What's the problem?

public void reverse() {

        Vertex initialVertex = vertices.get(1);
        reverseVertex(initialVertex);
    }

    public void reverseVertex(Vertex initialV) {

        initialV.setVisitedForReverse(true);
        ArrayList<Vertex> neighbors = new ArrayList<Vertex>();
        for( Vertex v : initialV.getAdjacent()) {
            if( !v.isVisitedForReverse() ) {
                neighbors.add(v);
                v.getAdjacent().add(initialV);
                initialV.getAdjacent().remove(v);
            }
        }
        for(Vertex vert : neighbors) 
            reverseVertex(vert);
    }
3

3 Answers

0
votes

Because You are iterating over list of Vertexes and in same time modifing it

0
votes

Using for-each loop, you can't modify the collection while you iterate on it.

Consider using an Iterator explicitly. Assuming your iterator supports the remove() operation (check it), this should work:

Iterator<Vertex> it = initialV.getAdjacent().iterator();
while (it.hasNext()) {
    if (...)
        it.remove();
}

However, my response only refers to the technicality of the loop. You should make sure your reversal logic is correct and keeps the data structure consistent.

0
votes

If performance is not important for your code, visit the adjacent nodes in one loop (don't remove any nodes from the adjacent list) and in another loop remove nodes (that have been added to the neighbours list) from the adjacent list.