【问题标题】:Get Enum instance [duplicate]获取枚举实例 [重复]
【发布时间】:2016-08-28 17:48:08
【问题描述】:

我有一个Enum

public enum Type {

    ADMIN(1), 
    HIRER(2), 
    EMPLOYEE(3);

    private final int id;

    Type(int id){
        this.id = id;       
    }

    public int getId() {
        return id;
    }
}

如何通过 id 属性获得 Type 枚举?

【问题讨论】:

标签: java enums


【解决方案1】:

Type 类中创建一个返回Enum 实例的方法:

Type get(int n) {
    switch (n) {
    case 1:
        return Type.ADMIN;
    case 2:
        return Type.EMPLOYEE;
    case 3:
        return Type.HIRER;
    default:
        return null;
    }

}

提示:您需要在switch-case 中添加default 或在方法末尾添加return null 以避免编译器错误。


更新(感谢@AndyTurner):

最好循环引用 id 字段,这样就不会重复 ID。

Type fromId(int id) {
    for (Type t : values()) {
        if (id == t.id) {
            return t;
        }
    }
    return null;
}

【讨论】:

  • 最好循环引用id字段,这样就不会重复ID。
  • @AndyTurner 更新了答案......但是......为什么你说我在复制身份证?我错过了什么?或者你的意思是每个id写一行??
  • @brimborium 是的,但那是彼得的回答......
  • @JordiCastilla 我刚看到。 ;)
  • 注意:每次调用 values() 时,它都会创建一个新的枚举值数组。它必须这样做,因为它不知道你是否要对其进行变异。
【解决方案2】:

您可以构建一个地图来进行此查找。

static final Map<Integer, Type> id2type = new HashMap<>();
static {
    for (Type t : values())
        id2type.put(t.id, t);
}
public static Type forId(int id) {
    return id2type.get(id);
}

【讨论】:

  • 我最喜欢这个解决方案。它很干净,对于任意大的枚举具有最佳性能。
【解决方案3】:

试试这个。我创建了一个使用 id 搜索类型的方法:

public static Type getType(int id) {

    for (Type type : Type.values()) {
        if (id == type.getId()) {
            return type;
        }
    }
    return null;
}

【讨论】:

    猜你喜欢
    • 2020-09-18
    • 2012-08-11
    • 1970-01-01
    • 2012-12-28
    • 2018-06-24
    • 2016-08-12
    • 1970-01-01
    • 2014-02-02
    相关资源
    最近更新 更多