我需要一些创建常量的帮助 我使用静态值创建了一个常量,如下所示
private static final Graph.Edge[] GRAPH = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
};
图形边缘方法
public static class Edge {
public final String v1, v2;
public final int dist;
public Edge(String v1, String v2, int dist) {
this.v1 = v1;
this.v2 = v2;
this.dist = dist;
}
}
如何在数组中提供数据时动态创建图形常量?
答案 0 :(得分:1)
如果您确定要将GRAPH作为常量,可以这样做:
//do not assign value yet
private static final Graph.Edge[] GRAPH;
...
//static initializer block
static{
//get a reference to the array you are talking about
//You can do whatever you like with tempGraph, not necessarily in one line
Graph.Edge[] tempGraph = {
new Graph.Edge("a", "b", 7),
new Graph.Edge("a", "c", 9),
new Graph.Edge("a", "f", 14),
new Graph.Edge("b", "c", 10),
new Graph.Edge("b", "d", 15),
};
//you set GRAPH to be the previously built tempGraph
//this is what you can do only one time, only in static initalizer block
GRAPH = tempGraph;
}