繁体   English   中英

将幻数映射为枚举值,反之亦然

[英]Mapping magic numbers to enum values, and vice-versa

在数据库中,我使用了这个,我想将其映射到State枚举,反之亦然。 我对undefined.code = 0的静态声明很感兴趣。 该声明实际上是做什么的?

package net.bounceme.dur.data;

public enum State {

    undefined(0), x(1), o(2), c(3), a(4), l(5), d(6);
    private int code = 0;

    static {
        undefined.code = 0;
        x.code = 1;
        o.code = 2;
        c.code = 3;
        a.code = 4;
        l.code = 5;
        d.code = 6;
    }

    State(int code) {
        this.code = code;
    }

    public int getCode() {
        return this.code;
    }

    public static State getState(int code) {
        for (State state : State.values()) {
            if (state.getCode() == code) {
                return state;
            }
        }
        return undefined;
    }

}

当前,此枚举工厂方法的用法如下:

  title.setState(State.getState(resultSet.getInt(5)));

但我会对所有其他选择感兴趣。

我删除了无用的静态块并改进了逆函数。

public enum State {

private static Map<Integer,State> int2state = new HashMap<>();

undefined(0), x(1), o(2), c(3), a(4), l(5), d(6);
private int code;

State(int code) {   // executed for *each* enum constant
    this.code = code;
    int2state.put( code, this ); 
}

public int getCode() {
    return this.code;
}

public static State getState(int code) {
    return int2state.get(code);
}
}

如果“代码”整数绝对是从0开始的序数,则可以省略Constructor参数,私有int代码和映射,如下所示:

int2state.put( this.ordinal(), this );

在您发布的代码中,静态代码行

undefined.code = 0;

它访问undefined的枚举常量,并盲目地将可变域code的值从00 基本上,常量在这里定义

undefined(0)

代码为0 x1同样如此。 等等。

好吧,它的确与构造函数具有相同的作用-设置与每个枚举值关联的code

在您的示例中, static { ... }块是多余的(不必要),应将其删除,因为它会复制以underfined(0)开头的行。

Enum用法变得棘手的地方在于查找(在您的情况下为getState(...)方法)。 case这里的语句实在复制代码中的第三次,你可能会更好,以建立一个Map ,需要一个代码( int ),并返回枚举( State ) -只是谷歌周围,有很多例子就如何做到这一点。

只是一个提示。 将您的getState(int)方法更改为

    public static State getState(int code) {
        for (State state : State.values()) {
            if (state.getCode() == code) {
                return state;
            }
        }
        return undefined; 
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM