Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting enum values into HashMap

Tags:

java

enums

map

I am doing a program in which i need to insert enum values into a HashMap. Can we really do that? I tried out it in many ways, but failed.

Can anyone please help me? Through the program I need to implement a HashMap containing 4 threadpools (whose names act as key) corresponding to which i have a ThreapoolExcecutor object.

Below given is my code :

public class MyThreadpoolExcecutorPgm {
    enum ThreadpoolName
    {
        DR,
        PQ,
        EVENT,
        MISCELLENEOUS;
    }
    private static String threadName;
    private static HashMap<String, ThreadPoolExecutor> threadpoolExecutorHash;

    public MyThreadpoolExcecutorPgm(String p_threadName) {
        threadName = p_threadName;

    }

    public static void fillthreadpoolExecutorHash() {
        int poolsize = 3;
        int maxpoolsize = 3;
        long keepAliveTime = 10;
        ThreadPoolExecutor tp = null;
        threadpoolExecutorHash = new HashMap<String, ThreadPoolExecutor>();

        ThreadpoolName poolName ;
        tp = new ThreadPoolExecutor(poolsize, maxpoolsize, keepAliveTime,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5));

        threadpoolExecutorHash.put(poolName,tp);    //Here i am failing to implement currect put()


    }
like image 999
vidhya Avatar asked Feb 09 '11 07:02

vidhya


2 Answers

You may want to consider using an EnumMap instead of a HashMap here. EnumMap is much faster and more space-efficient than a HashMap when using enumerated values, which seems to be precisely what you're doing here.

like image 141
templatetypedef Avatar answered Oct 09 '22 23:10

templatetypedef


Sure, it's possible to have enums as keys in a Map.

You get an error because the threadpoolExecutorHash maps from Strings to ThreadPoolExecutors, and it fails because you're trying to insert a String (poolName) as key.

Just change from

threadpoolExecutorHash = new HashMap<String, ThreadPoolExecutor>();

to

threadpoolExecutorHash = new HashMap<ThreadpoolName, ThreadPoolExecutor>();

As mentioned by @templatetypedef, there is even a special Map implementation, EnumMap tailored for using enums as keys.

like image 3
aioobe Avatar answered Oct 10 '22 01:10

aioobe