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()
}
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.
Sure, it's possible to have enums as keys in a Map.
You get an error because the threadpoolExecutorHash
maps from String
s to ThreadPoolExecutor
s, 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With