5

I have the following enum in my java android application:

static enum PaymentType
{           
    Scheme(0), Topup(1), Normal(2), Free(3), Promotion(4), Discount(5), Partial(6),
    Refund(7), NoShow(8), Prepay(9), Customer(10), Return(11), Change(12), PettyCash(13),
    StateTax(14), LocalTax(15), Voucher(16), Membership(17), Gratuity(18), Overpayment(19),
    PrepayTime(20), HandlingFee(21);

    private int value;

    private PaymentType(int i) {
        value = i;
    }
    public int getValue() {
        return value;
    }
}

I use this enum alot to find out the integer value of one of these string labels, for example int i = Lookups.PaymentType.Voucher.getValue();.

How can I do this the other way around? I have an integer value from a database and I need to find which string that corresponds to.

4

2 回答 2

7

你应该做这样的事情(静态初始化块应该在最后!在你的情况下,只需用数字替换“asc”和“desc”,或添加任何其他字段):

public enum SortOrder {
    ASC("asc"),
    DESC("desc");

    private static final HashMap<String, SortOrder> MAP = new HashMap<String, SortOrder>();

    private String value;

    private SortOrder(String value) {
        this.value = value;
    }

    public String getValue() {
        return this.value;
    }

    public static SortOrder getByName(String name) {
        return MAP.get(name);
    }

    static {
        for (SortOrder field : SortOrder.values()) {
            MAP.put(field.getValue(), field);
        }
    }
}

之后,只需调用:

SortOrder asc = SortOrder.getByName("asc");
于 2013-09-19T10:38:25.157 回答
0

ordinal()索引值返回枚举:

type = PaymentType.values()[index];

但是,请记住,当序数存储在其他任何地方(例如数据库)时,这很脆弱。如果索引号发生变化,您将得到无效的结果。

要获得更可靠的查找表,请使用 Map。

于 2013-09-19T10:43:30.770 回答