我正在做一个程序,我需要将枚举值插入HashMap。我们真的能这样做吗?我在很多方面尝试过它,但失败了。
任何人都可以帮助我吗?通过该程序,我需要实现一个包含4个线程池(其名称作为键)的HashMap,对应于我有一个ThreapoolExcecutor对象。
以下是我的代码:
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()
}
答案 0 :(得分:7)
您可以考虑在此处使用EnumMap
代替HashMap
。使用枚举值时,EnumMap
比HashMap
更快,更节省空间,这似乎正是您在这里所做的。
答案 1 :(得分:3)
当然,可以将枚举作为地图中的键。
由于threadpoolExecutorHash
从String
映射到ThreadPoolExecutor
,因此您收到错误,因为您尝试插入String
({{1} }})作为关键。
从
改变poolName
到
threadpoolExecutorHash = new HashMap<String, ThreadPoolExecutor>();
正如@templatetypedef所提到的,甚至还有一个特殊的Map实现,EnumMap
专门用于将枚举用作键。
答案 2 :(得分:0)
您使用String作为HashMap的键,您应该使用Enum类。您的代码应如下所示:
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()
}