1

我正在使用 Java Jung 2.01 图形包在图论中进行一些分析。我的算法采用 a Forest<V, E>,然后我可以转换为 a DelegateForest<V,E>,因此我可以使用该getTrees()方法获取森林组件的实例。我的算法是递归的,将在该getTrees()方法的每个组件上执行。

所以,问题是返回类型getTrees()是一个集合,Tree<V, E>因为我的算法需要一个Forest<V, E>(并且在某些时候强制转换为DelegateForest<V, E>)并且我希望在我的森林的每个树组件上执行我的算法,我得到一个 ClassCastException 说明我不能从 转换DelegateTree<V, E>DelegateForest<V, E>

这是我的一些代码:ArrayList<Forest<String, Integer>> treeComps = new ArrayList<Forest<String, Integer>>(forest.getTrees());

第一行只是将森林的树组件存储到一个 ArrayList 中。

((DelegateForest)forest).removeVertex(vertexCentralities.first().getKey(), false);

此演员表来自我的算法,该算法删除了树中的一个顶点,并保留了该顶点的子树。这就是为什么我需要演员DelegateForest<V, E>

  1. 如何从我的森林中提取树木,使树木具有类型Forest<V,E>,以便我DelegateForest<V, E>以后可以毫无问题地处理?
  2. 我需要修改源代码吗?
  3. 还有其他想法吗?
4

1 回答 1

0

You cannot cast a DelegateTree to a DelegateForest or vice versa, you can however cast both of them to a Forest, since they both implement that interface.

Since your algorithm takes a Forest I would expect that you could call the following method with delegateForest.getTrees(). And as the two-argument removeVertex(..., ...) method isn't specified on an interface, the easiest solution is probably to be inspired by the corresponding code on the DelegateForest and implement it locally.

public void doAlgorithm( Collection<Tree<K,V>> trees )
{
    for ( Tree<K,V> f : tree )
    {
        // algorithm here - tree is a Forest, and likely a DelegateTree
        removeVertex( tree );
    }
}

private removeVertex( Forest forest )
{
     // As per implementation in DelegateForest...
}

Cheers,

于 2012-10-19T12:04:46.793 回答