枚举中 fromValue() 方法的复杂性 class

Complexity of fromValue() method in enumeration class

我有一个 class 这样的:

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)?

谢谢。

地图是静态对象。此外,它由静态代码块中的代码填充。静态代码块每 class 只调用一次。没有理由多次生成地图。

这意味着你的第二个 fromValue(),即 O(n),在性能方面将比原来的 fromValue() 慢,即 O(1)。