将枚举值插入HashMap

时间:2011-02-09 07:50:44

标签: java enums map

我正在做一个程序,我需要将枚举值插入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()


    }

3 个答案:

答案 0 :(得分:7)

您可以考虑在此处使用EnumMap代替HashMap。使用枚举值时,EnumMapHashMap更快,更节省空间,这似乎正是您在这里所做的。

答案 1 :(得分:3)

当然,可以将枚举作为地图中的键。

由于threadpoolExecutorHashString映射到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()
}