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

标签 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 = 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/

相关文章:

javascript - TSP-like Puzzle 的求解器,可能在 Javascript 中

c++ - 通过从每一行中选择1个元素来查找2d数组中的最低和

algorithm - 复杂算法递推关系

algorithm - 使用 STL 运行长度使用 std::adjacent_find 对字符串进行编码

algorithm - 计算每个节点的邻居度数之和?

c++ - 如何找到覆盖有向循环图中所有节点的最短路径?

c# - 如何确定所有排列 &|层次结构中的组合

algorithm - 许多答案或多个参数情况下的计算复杂度

javascript - 在 Javascript 数组中查找元素的有效方法

sql - GroupBy 操作的渐近复杂度是多少?