5

我已经实现了这个图:

ListenableDirectedWeightedGraph<String, MyWeightedEdge> g = 
    new ListenableDirectedWeightedGraph<String, MyWeightedEdge>(MyWeightedEdge.class); 

为了显示类名的含义;一个简单的可听有向加权图。我想更改边缘的标签而不是格式

return "(" + source + " : " + target + ")"; 

我希望它显示边缘的重量。我意识到节点上的所有操作,例如getEdgesWeight()方法,都是从图而不是边缘委托的。如何显示边缘的重量?我是否必须以某种方式将图表传递到边缘?

任何帮助表示赞赏。

4

1 回答 1

2

I assume that the class MyWeightedEdge already contains a method such as

public void setWeight(double weight)

If this is indeed the case, then what you need to do is:

Derive your own subclass from ListenableDirectedWeightedGraph (e.g., ListenableDirectedWeightedGraph). I would add both constructor versions, delegating to "super" to ensure compatibility with the original class.

Create the graph as in your question, but using the new class

ListenableDirectedWeightedGraph g = 
    new CustomListenableDirectedWeightedGraph(
        MyWeightedEdge.class);

Override the method setEdgeWeight as follows:

public void setEdgeWeight(E e, double weight) {
    super.setEdgeWeight(e, weight);
    ((MyWeightedEdge)e).setWeight(weight);
}

And, last but not least, override the toString method of the class MyWeightedEdge to return the label you want the edge to have (presumably including the weight, which is now available to it).

I hope this helps.

于 2008-12-03T16:59:10.773 回答