Re: [jgrapht-users] Bug in removeAllEdges?
Brought to you by:
barak_naveh,
perfecthash
From: John V. S. <js...@gm...> - 2006-11-26 14:47:41
|
Trevor Harmon wrote: > On Nov 25, 2006, at 10:49 PM, Trevor Harmon wrote: > >> But the following JGraphT program throws a >> ConcurrentModificationException: >> >> DirectedGraph<String, DefaultEdge> g = >> new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class); >> String s1 = "s1"; >> String s2 = "s2"; >> g.addVertex(s1); >> g.addVertex(s2); >> g.addEdge(s1, s2); >> g.edgesOf(s1).clear(); > > Oops, I don't think I tested this correctly. The above program doesn't > throw an exception. In fact, it doesn't do anything. The graph remains > unchanged! > > Also, replacing the edgesOf call with outgoingEdgesOf causes an > UnsupportedOperationException. > > The latter may be acceptable behavior, but surely the former is not. This one is easy to fix; we can just apply Collections.unmodifiableSet to the computed Set returned from edgesOf. Then you'll get the UnsupportedOperationException in all cases (at the price of one extra object allocation, and possible breakage for existing apps). >> Regardless of this problem, how is one supposed to remove all >> outgoing edges from a vertex? > > So far, the best I've come up with is this: > > removeAllEdges( new Vector<Edge>(outgoingEdgesOf(node)) ); > > where "Edge" is the edge class and "node" is a vertex instance. > > Unfortunately, this requires allocating a temporary vector and copying > every edge into it. Is there a more efficient way? There is no more efficient way (although you should be using ArrayList instead of Vector). This is a standard pattern for dealing with the same issue in the Java collection classes, and is used in the implementation for AbstractBaseGraph.removeVertex too. If you want, log an enhancement request for convenience methods to be added to the Graphs utility class (removeEdgesOf, removeOutgoingEdgesOf, and removeIncomingEdgesOf). If you were searching for them, others probably are too. JVS |