如何从Java中分配给它们的值中检索枚举常量?

时间:2013-12-20 22:48:53

标签: java enums

我试图通过分配给它的值来使Enum保持不变,但是不知道是否有任何内置API来执行此操作。我的枚举看起来像这样:

public enum VideoBandwidth {

    VIDEO_BW_AUTO(-1),
    VIDEO_BW_OFF(0),
    VIDEO_BW_2_MBPS(2000000),
    VIDEO_BW_500_KBPS(500000),
    VIDEO_BW_250_KBPS(250000);

    private final int bandwidth;

    private VideoBandwidth (final int value) {
        bandwidth = value;
    }

    public int getValue() {
        return bandwidth;
    }
}

如何通过分配给它的值“2000000”获得枚举常量VIDEO_BW_2_MBPS? 我知道如果值是0,1,2,3之类的顺序,我可以使用VideoBandwidth.values()[index]但是如果值不能用作索引,我如何得到常量?

4 个答案:

答案 0 :(得分:4)

public static VideoBandwidth withValue(int value) {
    for (VideoBandwidth v : values()) {
        if (v.bandwidth == value) {
             return v;
        }
    }
    throw new IllegalArgumentException("no VideoBandwidth with value " + value);
}

当然,您也可以将枚举值存储在内部Map中,例如,如果您想避免迭代和数组创建。

答案 1 :(得分:1)

实现自己的方法,迭代所有常量并返回适当的一个或null /某个异常。

public VideoBandwidth valueOf(int bandwidth) {
    for (VideoBandwidth videoBandwidth : values()) {
        if (videoBandwidth.bandwidth == bandwidth)
            return videoBandwidth;
    }
    throw new RuntimeException();
}

答案 2 :(得分:1)

只迭代一次!定义静态Map并在加载时将其填充到静态块中。

final static Map<Integer, VideoBandwidth> cache = new HashMap<>();
static {
    for(VideoBandwidth e: VideoBandwidth.values()) {
        cache.put(e.getValue(), e);
    }
}

public static VideoBandwidth fromValue(int value) {
    VideoBandwidth videoBandwidth = cache.get(value);
    if(videoBandwidth == null) {
        throw new RuntimeException("No such enum for value: " + value);
    }
    return videoBandwidth;
}

答案 3 :(得分:0)

使用地图:

public enum VideoBandwidth {

    VIDEO_BW_AUTO(-1),
    VIDEO_BW_OFF(0),
    VIDEO_BW_2_MBPS(2000000),
    VIDEO_BW_500_KBPS(500000),
    VIDEO_BW_250_KBPS(250000);

    private final int bandwidth;
    private static final Map<Integer, VideoBandwidth> map = new HashMap<Integer, VideoBandwidth>();

    private VideoBandwidth (final int value) {
        bandwidth = value;
        map.put(value, this);
    }

    public int getValue() {
        return bandwidth;
    }

    public static VideoBandwidth valueOf(int bandWidth) {
        return map.get(bandWidth);
    }
}