将特定字符串映射到常量整数?

Wil*_*lco 1 java string integer constants

给定一组特定的字符串,将它们映射到相应的整数集的最佳方法是什么?假设我有一个内部使用的几个整数常量的类,但是需要获取传入的外部字符串并确定它们映射到的正确的相应整数常量.

这是一个简化的例子:

public class Example {
    public static final int ITEM_APPLE = 0;
    public static final int ITEM_BANANA = 1;
    public static final int ITEM_GRAPE = 3;

    public void incomingData(String value) {
        // Possible values would be "apple", "banana", and "grape" in this case.
    }
}
Run Code Online (Sandbox Code Playgroud)

从该值到相应的整数常量,最合适的方法是什么?一个HashMap?或者以任何方式在静态成员中定义这些映射?另一个想法?

rsp*_*rsp 6

我会使用HashMap最接近你想要实现的,因此是一个可维护的解决方案.您可以定义静态HashMap:

Class Example {
    public static final int ITEM_APPLE = 0;
    public static final int ITEM_BANANA = 1;
    public static final int ITEM_GRAPE = 3;

    private static final Map<String, Integer> fruitCodes = new HashMap<String, Integer>();

    static {
        fruitCodes.put("apple", ITEM_APPLE);
        fruitCodes.put("banana", ITEM_BANANA);
        // ...
    }


    public void incomingData(String value) {
        // Possible values would be "apple", "banana", and "grape" in this case.
        Integer code = fruitCodes(value);

        if (null == code) {
            throw new IllegalArgumentException("Forbidden fruit: " + value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)