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

Algorithm 枚举类中fromValue()方法的复杂性,algorithm,complexity-theory,Algorithm,Complexity Theory,我有一门课是这样的: 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 =

我有一门课是这样的:

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);
}
因为似乎每次我们在第一个方法中调用fromValue时,它都会生成一个映射,所以它也是O(n)


谢谢。

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


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

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

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

public static returnCode fromValue(String code) {
        for (returnCode returnCode : returnCode.values()) {
            if (returnCode .code.equals(code)) {
                return returnCode ;
            }
        }
    }