我使用了这个示例代码:
https://github.com/jgrapht/jgrapht/wiki/DirectedGraphDemo创建有向图。在此示例中,创建的Digraph的顶点为Strings
。我需要顶点作为点,我在代码中使用iD指定(iD从0到3,因此它们是int
)。所以我修改了这个例子:
public class DirectedGraphDemo {
public static void graph(int ... iD) {
// constructs a directed graph with the specified vertices and edges
DirectedGraph<int, DefaultEdge> directedGraph =
new DefaultDirectedGraph<int, DefaultEdge>
(DefaultEdge.class);
directedGraph.addVertex(0);
directedGraph.addVertex(1);
directedGraph.addVertex(2);
directedGraph.addVertex(3);
directedGraph.addEdge(0,1);
directedGraph.addEdge(1,2);
directedGraph.addEdge(2,3);
// computes all the strongly connected components of the directed graph
StrongConnectivityInspector sci =
new StrongConnectivityInspector(directedGraph);
List stronglyConnectedSubgraphs = sci.stronglyConnectedSubgraphs();
// prints the strongly connected components
System.out.println("Strongly connected components:");
for (int i = 0; i < stronglyConnectedSubgraphs.size(); i++) {
System.out.println(stronglyConnectedSubgraphs.get(i));
}
System.out.println();
// Prints the shortest path from vertex 0 to vertex 3. This certainly
// exists for our particular directed graph.
System.out.println("Shortest path from 0 to 3:");
List path =
DijkstraShortestPath.findPathBetween(directedGraph, 0, 3);
System.out.println(path + "\n");
}
}
但是,我在第<:p>行收到错误“unexpected token int”
DirectedGraph<int, DefaultEdge> directedGraph =
我将方法的参数更改为int
,为什么我会收到此错误?
答案 0 :(得分:4)
您不能将基元类型用作泛型,因此请将其更改为Integer
。自动装箱将有效,因此您无需将其他所有内容更改为Integer
。
答案 1 :(得分:1)
在Java的泛型中,不允许使用诸如int
之类的基本类型作为类型参数。作为替代,您可以将Java的包装类型用于基本类型。在这里,您可以使用Integer
代替int
。
DirectedGraph<Integer, DefaultEdge> directedGraph = // ,...
Java的装箱/取消装箱功能将处理从int
到Integer
的转换并隐式返回。