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

通过整数获取对应枚举实例及相关抽象问题咨询

Java 枚举按自定义int字段查询实例最优实现方案

首先纠正一个认知误区:Java 所有枚举类都会由编译器自动生成public static T[] values()静态方法,直接调用就能获取包含该枚举所有实例的数组,不需要手动维护List/Set集合。
下面给出两种常用实现方案,按需选择即可:

方案1:遍历匹配(适合枚举项较少的场景)

直接利用values()返回的数组遍历匹配,代码实现简单,不需要额外维护缓存:

public static CreatureType getCreatureType(int number) {
    for (CreatureType type : CreatureType.values()) {
        if (type.getNumber() == number) {
            return type;
        }
    }
    // 这里不推荐返回null,建议抛非法参数异常,避免上层业务出现空指针
    throw new IllegalArgumentException("No CreatureType matches number: " + number);
}

方案2:静态Map缓存(推荐,适合枚举项多/查询频繁的场景)

在枚举内部维护一个静态Map存储int值和枚举实例的映射关系,类加载时一次性初始化完成,后续查询复杂度为O(1),性能远高于遍历方案:

public enum CreatureType {

    POKE_PIG(1, "Piggley"), POKE_COW(2, "Cowbert");

    private int number;
    private String name;
    // 静态缓存映射
    private static final Map<Integer, CreatureType> NUMBER_TYPE_MAP;

    static {
        NUMBER_TYPE_MAP = new HashMap<>();
        for (CreatureType type : CreatureType.values()) {
            // 如果有重复的number值,初始化时就会报错,提前发现枚举定义问题
            if (NUMBER_TYPE_MAP.containsKey(type.getNumber())) {
                throw new IllegalStateException("Duplicate number found: " + type.getNumber());
            }
            NUMBER_TYPE_MAP.put(type.getNumber(), type);
        }
    }

    CreatureType(int number, String name) {
        this.number = number;
        this.name = name;
    }

    public int getNumber() {
        return number;
    }

    public String getName() {
        return name;
    }

    public static String getName(CreatureType type) {
        return type.getName();
    }

    public static int getNumber(CreatureType type) {
        return type.getNumber();
    }

    // 对外暴露的查询方法
    public static CreatureType getCreatureType(int number) {
        CreatureType type = NUMBER_TYPE_MAP.get(number);
        if (type == null) {
            throw new IllegalArgumentException("No CreatureType matches number: " + number);
        }
        return type;
    }
}

两种方案对比

  • 遍历方案代码量小,适合枚举项少于10个、调用频率低的场景,维护成本更低
  • Map缓存方案性能更高,且能在类加载阶段就检查出重复的number定义问题,更适合生产环境使用
  • 两种方案都比switch写法可维护性高,新增枚举项时不需要修改查询逻辑,自动适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:36:03