使用JUNG2将节点添加到集合中

问题描述:

我正在尝试添加一个像这样的节点(C.add(n)))

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

我有这个问题:

线程"main"中的异常java.util.Collections $ UnmodifiableCollection.add(未知源)处的java.lang.UnsupportedOperationException

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

非可执行代码示例:

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); }
}

您正尝试使用 UndirectedSparseMultigraph.getNeighbors(V vertex)获取此方法返回的 Vertices 不可修改的集合

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);
  }

一样

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

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

根据您的评论,它表明您正在尝试将节点 n 添加到其 neighbors 的集合中.如果是这种情况,请尝试更换

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)))

使用

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

添加一个自交点.