【问题标题】:java method using generics to convert Enumeration to HashMapjava方法使用泛型将Enumeration转换为HashMap
【发布时间】:2012-11-06 18:50:22
【问题描述】:

我正在尝试抽象一种方法,该方法使用枚举中的整数、字符串值加载静态哈希图。我的具体方法是这样的

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

【问题讨论】:

  • 你的问题是?这甚至不是一种方法……
  • 我不认为将静态块与抽象方法混合在一起是个好主意。
  • 显示MyEnum 的来源,以及足够的上下文让我们能够理解您的要求。
  • 你有什么问题?您面临的具体问题在哪里?

标签: java generics hashmap enumeration using


【解决方案1】:

这里有一个通用的方法可以为你做这件事。

注意你还没有说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;
}

注意允许类型绑定到 both Enumeration HasIntValue

的语法

【讨论】:

  • 为什么E 是自引用的?您是否将EnumerationEnum 混淆了?你所拥有的类似于声明&lt;I extends Iterable&lt;I&gt; &amp; HasIntValue&gt;
猜你喜欢
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-04
  • 1970-01-01
相关资源
最近更新 更多