-1

我正在尝试抽象一种方法,该方法从枚举中加载带有整数、字符串值的静态哈希图。我的具体方法看起来像这样

public static Map<Integer, String> myMap = new HashMap<Integer, String>;
static{
    Enumeration<MyEnum> enumTokens = MyEnum.getTokens(); //returns an enumeration of 'MyEnum'
    //like to abstract  the following into a method
    while (enumTokens.hasMoreElements()){
        MyEnum element = (MyEnum) enumTokens.nextElement();
        myMap.put(element.intValue(), element.toString());
    }
}
4

1 回答 1

0

Here's a generic method that will do it for you.

Note that you haven't said what the significance of intValue() is, so I've created an interface for it.

interface HasIntValue {
    int intValue();
}

public static <E extends Enumeration<E> & HasIntValue> Map<Integer, String> convertToMap(E e) {
    Map<Integer, String> map = new HashMap<Integer, String>();
    while (e.hasMoreElements()){
        E element = e.nextElement();
        map.put(element.intValue(), element.toString());
    }
    return map;
}

Note the syntax that allows a type bound to both Enumeration and HasIntValue

于 2012-11-06T19:34:43.470 回答