2015-11-19 51 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; 
}