Java枚举-通过值查找对应的枚举

Python微信订餐小程序课程视频

https://edu.csdn.net/course/detail/36074

Python实战量化交易理财系统

https://edu.csdn.net/course/detail/35475

一、背景

Java 枚举是一个特殊的类,一般表示一组常量,比如一年的 4 个季节,一个年的 12 个月份,一个星期的 7 天,方向有东南西北等。

最近工作中,对接了很多其他的系统,发现对接的同一个系统都有不同的环境(开发、测试、正式环境),并且每个环境的配置信息通常不会修改,所以发现用枚举 做配置项,使用起来比较简洁,不同的环境配置 只需多定义一个枚举值就搞定了。

其中使用枚举就会涉及到通过传入的值,返回对应的枚举。

二、通过一个值 ,查询返回对应的枚举(示例代码)

2.1、枚举类
@Getter
public enum CustomType {
    TEST("test","测试","111"),
    DEV("dev","开发","222");

    String typeCode;
    String typeName;
    String orgId;

    CustomType(String typeCode, String typeName, String orgId) {
        this.typeCode = typeCode;
        this.typeName = typeName;
        this.orgId = orgId;
    }
}

2.2、常用的枚举方法;values(), ordinal() 和 valueOf() 方法

enum 定义的枚举类默认继承了 java.lang.Enum 类,并实现了 java.lang.Seriablizable 和 java.lang.Comparable 两个接口。

values(), ordinal() 和 valueOf() 方法位于 java.lang.Enum 类中:

  • values() 返回枚举类中所有的值。
  • ordinal()方法可以找到每个枚举常量的索引,就像数组索引一样。
  • valueOf()方法返回指定字符串值的枚举常量。

传入值查询枚举,就是通过values()方法,返回所以枚举,再遍历全部枚举,只要传入的参数值 跟当前枚举的值跟相同,就返回当前枚举;

2.3、通过传入一个或者多个值,返回对应的枚举
    public CustomType find(String typeCode){
        for (CustomType value : CustomType.values()) {
            if(typeCode.equals(value.getTypeCode())){
                return value;
            }
        }
        //根据自身的业务 查不到可以返回null,或者抛出异常。
        return null;
    }

    public CustomType find(String orgId,String typeCode){
        if(orgId == null || typeCode == null){
            return null;
        }

        for (CustomType value : CustomType.values()) {
            if(orgId.equals(value.getOrgId()) &&
                    typeCode.equals(value.getTypeCode())){
                return value;
            }
        }
        //根据自身的业务 查不到可以返回null,或者抛出异常。
        return null;
    }

三、查找优化

每次通过values()方法遍历查找,时间复杂度是O(n),而通过HashMap查找,时间复杂度是O(1)。

虽说枚举的数量通常都不会很庞大,每次通过values()方法遍历查找速度也很快。用HashMap会多占用一点点内存,但是考虑到这一点内存能从时间复杂度是O(n)降到O(1),这种惠而不费的事,还是可以花时间去优化代码的。

    private static Map<String,CustomType> orgCustomType = new HashMap<>();
    static {
        for (CustomType value : CustomType.values()) {
            orgCustomType.put(value.getOrgId(),value);
        }
    }

    public CustomType find(String orgId){
        return orgCustomType.get(orgId);
    }

猜你喜欢

转载自blog.csdn.net/pythonxxoo/article/details/122757988