Java枚举反向查找最佳做法 [英] Java enum reverse look-up best practice

查看:839
本文介绍了Java枚举反向查找最佳做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到它在博客上建议以下是使用Java枚举中的 getCode(int)进行反向查找的合理方法:

I saw it suggested on a blog that the following was a reasonable way to do a "reverse-lookup" using the getCode(int) in a Java enum:

public enum Status {
    WAITING(0),
    READY(1),
    SKIPPED(-1),
    COMPLETED(5);

    private static final Map<Integer,Status> lookup 
            = new HashMap<Integer,Status>();

    static {
        for(Status s : EnumSet.allOf(Status.class))
            lookup.put(s.getCode(), s);
    }

    private int code;

    private Status(int code) {
        this.code = code;
    }

    public int getCode() { return code; }

    public static Status get(int code) { 
        return lookup.get(code); 
    }
}

对我来说,静态地图和静态初始值设定看起来像个坏主意,我的第一个想法就是如下编码:

To me, the static map and the static initializer both look like a bad idea, and my first thought would be to code the lookup as so:

public enum Status {
    WAITING(0),
    READY(1),
    SKIPPED(-1),
    COMPLETED(5);

    private int code;

    private Status(int code) {
        this.code = code;
    }

    public int getCode() { return code; }

    public static Status get(int code) { 
        for(Status s : values()) {
            if(s.code == code) return s;
        }
        return null;
    }
}

任何一种方法都有明显的问题,有一种建议的方法来实现这种查找?

Are there any obvious problems with either method, and is there a recommended way to implement this kind of lookup?

推荐答案

虽然它的开销较高,静态地图很好,因为它提供定期查询代码。您的实现的查找时间随着枚举中的元素数量线性增加。对于小枚举,这根本不会有显着的贡献。

Though it has higher overhead, the static map is nice because it offers constant-time lookup by code. Your implementation's lookup time increases linearly with the number of elements in the enum. For small enums, this simply will not contribute significantly.

两个实现(可以说是与一般的Java枚举有关)的一个问题是,真的有一个隐藏的额外值状态可以执行: null 。根据业务逻辑的规则,当查找失败时返回一个实际枚举值或者抛出一个异常可能是有意义的。

One issue with both implementations (and, arguably, with Java enums in general) is that there's really a hidden extra value that a Status can take on: null. Depending on the rules of the business logic, it may make sense to return an actual enum value, or throw an Exception, when the lookup "fails."

这篇关于Java枚举反向查找最佳做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆