Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic enum parameter in java. Is this possible?

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

This is what I have so far, (for a specific enum), can my function enumToMap be rewritten generally to accept any enum type?

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.

like image 776
Chris Avatar asked Sep 22 '10 15:09

Chris


People also ask

Can enum be generic Java?

The enum is a default subclass of the generic Enum<T> class, where T represents generic enum type. This is the common base class of all Java language enumeration types. The transformation from enum to a class is done by the Java compiler during compilation. This extension need not be stated explicitly in code.

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.

Can we pass parameter to enum in Java?

So no, you can't have different values of a specific enum constant. Save this answer.

Which types can be generic parameters?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


2 Answers

Change the signature of your enumToMap method to something like this:

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

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

In your main method you can then call this method like:

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

As seanizer mentions, you should also be using EnumMap as the Map implementation rather than HashMap.

like image 187
ColinD Avatar answered Sep 28 '22 07:09

ColinD


Don't use a HashMap with enums, this is what an EnumMap was designed for.

As written in the Map section of the Collection Trail in the Sun Java Tutorial:

EnumMap, which is internally implemented as an array, is a high-performance Map implementation for use with enum keys. This implementation combines the richness and safety of the Map interface with a speed approaching that of an array. If you want to map an enum to a value, you should always use an EnumMap in preference to an array.

like image 23
Sean Patrick Floyd Avatar answered Sep 28 '22 08:09

Sean Patrick Floyd