Before I posted this question, I read the post in here. But for this particular problem, I really do not know how I can apply the same philosophy ?
In the following problem, my variable graph
has the following structure: HashMap<Integer, ArrayList<Integer>>
.
And u
and v
has type int
. Basically, I want to remove the value v
in the arraylists with a key value of i
, where i
appears in the arraylist of v
.
So, if the integer i
appears in the arraylist of v
, we get the arraylist of i
in the graph and remove the value v
from it.
This sounds really complicated. But I am stuck at this ConcurrentModificationException for some time now.
public int random_contraction_algo(){
while(graph.size() > 2){
int u = select_remaining_edges_at_random(new ArrayList<Integer> (graph.keySet()));
int v = select_remaining_edges_at_random(graph.get(u));
merge(u,v);
}
return -1;
}
// select a pair of vertices from an edge
public int select_remaining_edges_at_random(ArrayList<Integer> vertices){
int index = (int)(Math.random() * (vertices.size()));
return vertices.get(index);
}
public void merge(int u, int v){
graph.get(u).addAll(graph.get(v));
// remove self-loops
graph.get(u).removeAll(Collections.singleton(u));
graph.get(u).removeAll(Collections.singleton(v));
// make sure all the edges of v are connected to u instead v
for(Iterator<Integer> iterator = graph.get(v).iterator(); iterator.hasNext();){
Integer i = iterator.next();
graph.get(i).remove((Integer) v);
graph.get(i).add(u);
}
// remove key
graph.remove(v);
}
UPDATE: I really appreciate your answers. However, I realize I forgot to show you guys that there is an outer loop in my code.
I tried implementing your solutions but the ConcurrentModificationException still occurs.
These are the error messagaes:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
at java.util.ArrayList$Itr.next(ArrayList.java:836)
at HashMapOfArrayList.merge(ArraylistOfArrayList.java:96)
at HashMapOfArrayList.random_contraction_algo(ArraylistOfArrayList.java:69)
at RunAlgo.main(ArraylistOfArrayList.java:111)