You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java枚举中初始化并填充LinkedHashMap(规避内存泄漏)

解决方案:在枚举内部初始化LinkedHashMap的几种方式

方法1:利用Map.ofEntries() + LinkedHashMap构造器(推荐Java 9+)

首先明确:你担心的顺序问题不存在。Map.ofEntries()返回的是按插入顺序迭代的不可变Map,将它传入LinkedHashMap的构造器时,LinkedHashMap会按照这个迭代顺序插入元素,完全保留原有的插入顺序。

代码示例:

import java.util.LinkedHashMap;
import java.util.Map;
import static java.util.Map.entry;

enum Recipe {
    PANCAKES(true, new LinkedHashMap<>(Map.ofEntries(
        entry("Pancake Mix", "Pour"),
        entry("Water", "Mix with"),
        entry("Pan", "Put mixture onto")
    ))),
    SANDWICH(true, new LinkedHashMap<>(Map.ofEntries(
        entry("Bread", "Take two slices"),
        entry("Ham", "Place between slices")
    ))),
    STEW(false, new LinkedHashMap<>(Map.ofEntries(
        entry("Meat", "Brown in pot"),
        entry("Vegetables", "Add and simmer")
    )));

    private final boolean tasty;
    private final LinkedHashMap<String, String> directions;

    Recipe(boolean tasty, LinkedHashMap<String, String> directions) {
        this.tasty = tasty;
        this.directions = directions;
    }

    // Getter
    public LinkedHashMap<String, String> getDirections() {
        return directions;
    }
}

这个方式简洁,没有双花括号的隐患,且完全在枚举内部完成初始化,后续扩展枚举常量时直接追加即可。

方法2:枚举内部静态工厂方法

如果觉得上面的写法有点冗长,可以在枚举内部写一个静态方法,专门负责创建并填充LinkedHashMap,这样枚举常量的初始化代码更清晰:

import java.util.LinkedHashMap;

enum Recipe {
    PANCAKES(true, createDirections(
        "Pancake Mix", "Pour",
        "Water", "Mix with",
        "Pan", "Put mixture onto"
    )),
    SANDWICH(true, createDirections(
        "Bread", "Take two slices",
        "Ham", "Place between slices"
    )),
    STEW(false, createDirections(
        "Meat", "Brown in pot",
        "Vegetables", "Add and simmer"
    ));

    private final boolean tasty;
    private final LinkedHashMap<String, String> directions;

    Recipe(boolean tasty, LinkedHashMap<String, String> directions) {
        this.tasty = tasty;
        this.directions = directions;
    }

    // 静态工厂方法:接收键值对参数,创建并返回填充好的LinkedHashMap
    private static LinkedHashMap<String, String> createDirections(String... entries) {
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        for (int i = 0; i < entries.length; i += 2) {
            if (i + 1 < entries.length) {
                map.put(entries[i], entries[i + 1]);
            }
        }
        return map;
    }

    // Getter
    public LinkedHashMap<String, String> getDirections() {
        return directions;
    }
}

这个方法的好处是代码可读性更强,新增枚举常量时只需要按键值对顺序传入参数即可,无需重复写Map的创建逻辑。需要注意的是,传入的参数必须是偶数个,否则最后一个键会没有对应的值(可根据需求添加参数校验)。

方法3:静态块初始化(适合复杂逻辑)

如果你的填充逻辑比较复杂(比如需要条件判断、循环生成等),可以用静态块来给每个枚举常量的directions赋值:

import java.util.LinkedHashMap;

enum Recipe {
    PANCAKES(true, null),
    SANDWICH(true, null),
    STEW(false, null);

    private final boolean tasty;
    private LinkedHashMap<String, String> directions;

    Recipe(boolean tasty, LinkedHashMap<String, String> directions) {
        this.tasty = tasty;
        this.directions = directions;
    }

    // 静态块初始化每个枚举的directions
    static {
        // 初始化PANCAKES的步骤
        LinkedHashMap<String, String> pancakeDir = new LinkedHashMap<>();
        pancakeDir.put("Pancake Mix", "Pour");
        pancakeDir.put("Water", "Mix with");
        pancakeDir.put("Pan", "Put mixture onto");
        PANCAKES.directions = pancakeDir;

        // 初始化SANDWICH的步骤
        LinkedHashMap<String, String> sandwichDir = new LinkedHashMap<>();
        sandwichDir.put("Bread", "Take two slices");
        sandwichDir.put("Ham", "Place between slices");
        SANDWICH.directions = sandwichDir;

        // 初始化STEW的步骤
        LinkedHashMap<String, String> stewDir = new LinkedHashMap<>();
        stewDir.put("Meat", "Brown in pot");
        stewDir.put("Vegetables", "Add and simmer");
        STEW.directions = stewDir;
    }

    // Getter
    public LinkedHashMap<String, String> getDirections() {
        return directions;
    }
}

这种方式的灵活性最高,适合处理复杂的初始化逻辑,但缺点是初始化代码和枚举常量定义分离,扩展时需要同时修改静态块,不如前两种直观。


内容的提问来源于stack exchange,提问作者labradorEater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:15:31