Generic enum parameter in java. Is it possible?

I am trying to write a generic function that will accept any enumeration, and put the values ​​in the map for use in the drop-down list.

This is what I still have (for a specific enumeration), can my enumToMap function be rewritten at all to accept any type of enumeration?

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


    }

}

Thanks for any suggestions.

+5
source share
2 answers

Change the signature of your method enumToMapto the following:

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

Then you call e.values()instead enumType.getEnumConstants().

In your main method, you can call this method as follows:

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

seanizer EnumMap Map, HashMap.

+12

HashMap , EnumMap.

Trail Sun Java:

EnumMap, , Map . Map . , EnumMap .

+6

All Articles