静态初始化和仍为空指针异常

时间:2015-04-27 16:43:13

标签: java static

我遵循了从其他SO帖子构建静态hashmap的建议,但是当我尝试访问HashMap中的信息时,我现在有一个空的指向异常。有什么想法吗?

public final class EMUtil {
static private HashMap<String,TreeSet<String>> EMGroups;
static{
    HashMap<String,TreeSet<String>> EMGroups = new HashMap<String, TreeSet<String>>();

    TreeSet<String> temp=new TreeSet<String>();
    temp.addAll(returnArray("99201","99202","99203","99204","99205"));
    EMGroups.put("Set 1",temp);

    temp=new TreeSet<String>();
    temp.addAll(returnArray("99211","99212","99213","99214","99215"));
    EMGroups.put("Set 2",temp);

    ...
}

static public boolean isEM(String curCPT){
    if((curCPT.compareTo("99200")>0)&&(curCPT.compareTo("99311")<0)){
        for(TreeSet<String> value:EMGroups.values()){
            if(value.contains(curCPT)){
                return true;
            }
        }
    }
    return false;
}

任何想法是怎么回事?如果我试图拥有一组我可以访问的集合来检查一个字符串是否在该集合中的一个组/它所在的组中是否有更好的方法来构建它?

1 个答案:

答案 0 :(得分:3)

static{
    HashMap<String,TreeSet<String>> EMGroups = new HashMap<String, TreeSet<String>>();

此变量声明隐藏了您的静态EMGroups类成员。应该是:

static{
    EMUtil.EMGroups = new HashMap<String, TreeSet<String>>();

虽然你可以放弃'EMUtil。'