2015-11-19 50 views
0

我需要一些帮助,创建一个常数 我已经使用静态值如下创建图形不断动态

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

你打算怎样提供阵列?动态创建的常量听起来像是一个矛盾。也许你只是想要一个不是常量的静态变量。 – WillShackleford

回答

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; 
}