2010-09-22 60 views
5

我想写一个通用函数,它将接受任何枚举,并将这些值放入地图中,以便在下拉列表中使用。java中的泛型枚举参数。这可能吗?

这是我到目前为止,(对于特定的枚举),我的函数enumToMap一般可以重写为接受任何枚举类型?

import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.HashMap; 
import java.util.List; 
import java.util.Map; 

public class Main { 

    private enum testenum{ 
     RED,BLUE,GREEN 
    } 


    private static Map enumToMap(testenum e){ 
     HashMap result = new HashMap(); 
     List<testenum> orderReceiptKeys = Arrays.asList(e.values()); 
     List<String> orderReceiptValues = unCapsCase(orderReceiptKeys); 
     for(int i=0;i<orderReceiptKeys.size();i++){ 
      result.put(orderReceiptKeys.get(i), orderReceiptValues.get(i)); 
     } 
     return result; 
    } 

    /** 
    * Converts a string in the form of 'TEST_CASE' to 'Test case' 
    * @param s 
    * @return 
    */ 
    private static String unCapsCase(String s){ 
     StringBuilder builder = new StringBuilder(); 
     boolean first=true; 
     for(char c:s.toCharArray()){ 
      if(!first) 
       c=Character.toLowerCase(c); 
      if(c=='_') 
       c=' '; 
      builder.append(c); 
      first=false; 
     } 
     return builder.toString(); 
    } 


    /** 
    * Converts a list of strings in the form of 'TEST_CASE' to 'Test case' 
    * @param l 
    * @return 
    */ 
    private static List<String> unCapsCase(List l){ 
     List<String> list = new ArrayList(); 

     for(Object o:l){ 
      list.add(unCapsCase(o.toString())); 
     } 

     return list; 
    } 


    public static void main(String[] args) throws Exception { 

     try{ 
      testenum e=testenum.BLUE; 
      Map map = enumToMap(e); 
      for(Object k:map.keySet()){ 
       System.out.println(k.toString()+"=>"+map.get(k)); 
      } 
     }catch(Exception e){ 
      e.printStackTrace(); 
     } 


    } 

} 

感谢您的任何建议。

回答

12

更改您的enumToMap方法的签名是这样的:

private static <E extends Enum<E>> Map<E, String> enumToMap(Class<E> enumType) 

然后,你叫e.values()使用enumType.getEnumConstants()来代替。

在你的主要方法,你就可以调用此方法,如:

Map<testenum, String> map = enumToMap(testenum.class); 

由于seanizer提到,你也应该使用EnumMap作为Map实现,而不是HashMap

+0

完美!非常感谢。 – Chris 2010-09-22 15:55:49

+0

@Chris:请接受与检查的答案是否回答你的问题。谢谢! =) – ColinD 2010-09-22 15:59:58

+0

我不知道getEnumConstants()+1 – Wooff 2015-06-11 07:14:32

6

不要使用带枚举的HashMap,这是EnumMap的设计目的。

由于在Sun Java教程写在Map section of the Collection Trail

EnumMap,在内部 作为数组实现的,是与枚举键使用 高性能Map实施 。这个 实现将丰富性 和Map接口的安全性与接近数组的接口速度相结合。如果 要将枚举映射到值 ,则应始终使用EnumMap优先于 的数组。