如何使用Scala的GraphStream库



我尝试使用GraphStream库来查找图中2个节点之间的最短路径。最后,我能够打印路径的边缘(it.foreach(println)),但我不能一次访问一个元素。这是代码:

import org.graphstream.algorithm.Dijkstra;
import org.graphstream.graph.Edge;
import org.graphstream.graph.Graph;
import org.graphstream.graph.Node;
import org.graphstream.graph.Path;
import org.graphstream.graph.implementations.SingleGraph;
import scala.collection.JavaConverters._

object MainApp extends App{

        def exampleGraph():Graph={
                  val g:Graph = new SingleGraph("example");
                  g.addNode("N1_S1");
                  g.addNode("N1_J1");
                  g.addNode("N1_H1");
                  g.addNode("N1_J2");
                  g.addNode("N1_H2");
                  g.addNode("N1_W1");
                  var e:Edge=g.addEdge("N1_S1-N1_J1", "N1_S1", "N1_J1")
                  e.addAttribute("length",Int.box(6))
                  e=g.addEdge("N1_J1-N1_H1", "N1_J1", "N1_H1")
                  e.addAttribute("length",Int.box(8))
                  e=g.addEdge("N1_J1-N1_J2", "N1_J1", "N1_J2")
                  e.addAttribute("length",Int.box(8))
                  e=g.addEdge("N1_J2-N1_H2", "N1_J2", "N1_H2")
                  e.addAttribute("length",Int.box(4))
                  e=g.addEdge("N1_J2-N1_W1", "N1_J2", "N1_W1")
                  e.addAttribute("length",Int.box(10))
                  return g
        }
    val g:Graph = exampleGraph();
    g.display(false);
    val dijkstra:Dijkstra = new Dijkstra(Dijkstra.Element.EDGE, null, "length");
    dijkstra.init(g);
    dijkstra.setSource(g.getNode("N1_S1"));
    println(dijkstra.getPath(g.getNode("N1_W1")));
    val myPath:Path=dijkstra.getPath(g.getNode("N1_W1"))
    val it=(myPath.getEachEdge).asScala
    println("edges")
    it.foreach(println)
}

问题是getEachEdge的原型是getEachEdge[T <: Edge](): Iterable[_ <: T],而asScala返回的是Iterable[_ <: Nothing]。最后一个问题是"如何访问最短路径中的每个元素?"

我不知道为什么,但是你必须显式地注释类型。

myPath.getEachEdge[Edge].asScala

如果指定了错误的子类型,可能会得到运行时强制转换异常。

抛出ClassCastException:

@ trait OtherEdge extends Edge
defined trait OtherEdge
@ myPath.getEachEdge[OtherEdge].asScala.head
java.lang.ClassCastException: org.graphstream.graph.implementations.AbstractEdge cannot be cast to $sess.cmd17$OtherEdge
  $sess.cmd18$.<init>(cmd18.sc:1)
  $sess.cmd18$.<clinit>(cmd18.sc:-1)

尝试用类型注释帮助编译器:

val it: Iterable[Edge] = myPath.getEachEdge.asScala

相关内容

  • 没有找到相关文章

最新更新