我在我的Go程序中有一个类似的变量,并试图像在Java中那样做;
var (
STATUS = map[int]string{
200: "OK",
201: "Created",
202: "Accepted",
304: "Not Modified",
400: "Bad Request",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
405: "Resource Not Allowed",
406: "Not Acceptable",
409: "Conflict",
412: "Precondition Failed",
415: "Bad Content Type",
416: "Requested Range Not Satisfiable",
417: "Expectation Failed",
500: "Internal Server Error",
}
)我尝试使用HashMap或其他数组内容,但不能使用,因为它将是Response类的属性,必须在开始时定义,如;
package http;
class Response {
// here define filling it e.g STATUS = new Array(200, "OK", ...) etc..
... STATUS ...
}是的,我可以使用HashMap在构造函数中填充它,但是我不能像这样得到例如"OK“:String status = STATUS[200]。
发布于 2016-08-19 07:52:38
您可以使用静态类初始化器并使用HashMap,就像您尝试过的那样。
class Response
{
public static final Map<Integer,String> STATUS;
static{
STATUS=new HashMap<>();
STATUS.put(200,"OK");
STATUS.put(201,"Created");
// ...
}
}示例用法:
Response.STATUS.get(200); // will return "OK"如果您愿意,您甚至可以使用Collection.unmodifiableMap()使其不可修改。这就是我要做的。所以上面的静态类初始化器现在看起来像这样:
static{
HashMap<Integer,String> statusValues=new HashMap<>();
statusValues.put(200,"OK");
statusValues.put(201,"Created");
// ...
STATUS=Collections.unmodifiableMap(statusValues);
}https://stackoverflow.com/questions/39029088
复制相似问题