Insert enum values ​​in a HashMap

I am making a program in which I need to embed enum values ​​in a HashMap. Can we do this? I tried it in many ways, but could not.

Can anybody help me? Through the program, I need to implement a HashMap containing 4 thread pools (whose names act as key) for which I have a ThreapoolExcecutor object.

Below 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() } 
+4
source share
3 answers

You might want to use EnumMap instead of HashMap here. EnumMap much faster and more economical than a HashMap when using enumerated values, which seems to be exactly what you are doing here.

+7
source

Of course, it is possible to have transfers in the form of keys on the map.

You get an error because threadpoolExecutorHash displays from String to ThreadPoolExecutor s, and it fails because you are trying to insert the String ( poolName ) key.

Just change

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

to

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

As mentioned in @templatetypedef, there is even a special implementation of the EnumMap map designed to use enumerations as keys.

+3
source

You use String as the key of your HashMap, you should use the Enum class instead. Your code should look like this:

 public class MyThreadpoolExcecutorPgm { enum ThreadpoolName { DR, PQ, EVENT, MISCELLENEOUS; } private static String threadName; private static HashMap<ThreadpoolName, 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<ThreadpoolName, 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() } 
0
source

Source: https://habr.com/ru/post/1338986/


All Articles