如何使用Scala的GraphStream库

时间:2016-10-29 12:52:18

标签: java scala graph scala-collections 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]。所以最后一个问题是&#34;我如何访问最短路径的每个元素?&#34;

2 个答案:

答案 0 :(得分:2)

我不知道为什么,但你必须明确注释该类型。

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)

答案 1 :(得分:1)

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

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