2012-11-06 42 views
-1

我想從一個枚舉中抽取一個使用Integer,String值加載靜態HashMap的方法。我的具體方法看起來像這樣使用泛型將枚舉轉換爲HashMap的java方法

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()); 
    } 
} 
+3

而且你的問題是一個類型的語法?這甚至不是一種方法...... – home

+0

我認爲將靜態塊與抽象方法混合並不是一個好主意。 – kosa

+1

顯示「MyEnum」的來源,以及足夠的上下文讓我們能夠理解您要求的內容。 –

回答

0

這是一個通用的方法,將爲您做。

請注意,您尚未說明intValue()的重要性,因此我爲它創建了一個接口。

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; 
} 

注意,允許勢必EnumerationHasIntValue

+0

爲什麼'E'自引用?你用'Enum'搞混了Enumeration嗎?你有什麼類似於聲明'&HasIntValue>'。 –