gpt4 book ai didi

java - 动态创建图形常量

转载 作者:行者123 更新时间:2023-12-01 10:51:57 25 4
gpt4 key购买 nike

我需要一些帮助来创建常量我使用静态值创建了一个常量,如下所示

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

当在数组中提供数据时,如何动态创建图形常量?

最佳答案

如果您确定希望 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;
}

关于java - 动态创建图形常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33816009/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com