0

I am trying to add a node like this ( C.add(n)))

I have this problem:

Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Unknown Source))

Non-executable code example:

UndirectedSparseMultigraph<MyNode, MyLink> g = getgraph1();
Collection<MyNode> c = null ;
for( MyNode n : g.getVertices() ){
  if( n.id == 3 ){
    c = g.getNeighbors(n);
    System.out.println(C); C.add(n); }
}
Florent
  • 12,310
  • 10
  • 49
  • 58
Delel
  • 1
  • 1

1 Answers1

1

You are trying to use UndirectedSparseMultigraph.getNeighbors(V vertex) to get the Vertices this method returns an unmodifiable collection

  public Collection<V> getNeighbors(V vertex) {
  ...
    return Collections.unmodifiableCollection(neighbors);
  }

As do

  public Collection<V> getVertices()
  {
    return Collections.unmodifiableCollection(vertex_maps.keySet());
  }

and

  public Collection<E> getEdges()
  {
    Collection<E> edges = new ArrayList<E>(directed_edges.keySet());
    edges.addAll(undirected_edges.keySet());
    return Collections.unmodifiableCollection(edges);
  }

Based on your comments it appers that you are trying to add a node n to the collection of its neighbors. If this is the case have your tried replacing

( C.add(n)))

with

g.addEdge(new MyLink(), n, n);

to add a self intersection.

GrahamA
  • 5,875
  • 29
  • 39
  • This is almost certainly the reason. To give some context, the collections were made to be unmodifiable because removing a vertex or edge, and adding an edge, requires some internal bookkeeping to keep the data structures in a good state. (Adding a vertex could be done via add() on the collection but for reasons of consistency it's also handled via a separate method, i.e., addVertex()). – Joshua O'Madadhain Aug 22 '12 at 21:24
  • UndirectedSparseMultigraph g = getgraph1(); Collection C = null ; for(MyNode n:g.getVertices()){ if(n.id==3){ C = g.getNeighbors(n); System.out.println(C); C.add(n); } //System.out.println("La collection est " +C); }} – Delel Aug 22 '12 at 23:22
  • Thanks . I'd like to construct a modifiable collection of node that is possible to add or delete some of its objects. this is my purpose. (why using g.adding()!! this node is a member of g) – Delel Aug 23 '12 at 14:04
  • @Delel I'm afraid that I don't really understand what you are trying to do. Can I suggest that you accept this answer (as it explains why your code resulted in an `Exception`) and then ask a new question the comments section is not the best place to continue. – GrahamA Aug 23 '12 at 19:12