我有这样一个类:
public enum ReturnCode{
Code1(
"Code1",
"Return this code when there is an erreur"
),
Code2(
"Code2",
"Return this code when everything ok"
);
ReturnCode(final String code, final String detail) {
this.code = code;
this.detail = detail;
}
private static Map<String, ReturnCode> map =
new HashMap<String, ReturnCode>();
static {
for (ReturnCode returnCode : ReturnCode.values()) {
map.put(returnCode.code, returnCode);
}
}
public static ReturnCode fromValue(String code) {
return map.get(code);
}
我只想知道在复杂性方面,它比 :
public static returnCode fromValue(String code) {
for (returnCode returnCode : returnCode.values()) {
if (returnCode .code.equals(code)) {
return returnCode ;
}
}
}
因为似乎每次我们在第一个方法中调用 fromValue 时,它都会生成一个映射,所以总的来说它也是 O(n)?
谢谢。
最佳答案
map 是静态对象。此外,它由静态代码块中的代码填充。每个类只调用一次静态代码块。没有理由多次生成 map 。
这意味着您的第二个 fromValue()
的复杂度为 O(n),将比原始的 fromValue()
的复杂度为 O(1) 慢在性能方面。
关于algorithm - 枚举类中 fromValue() 方法的复杂性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058206/