【问题标题】:Static Initialization and still null pointer exception [duplicate]静态初始化和仍然空指针异常[重复]
【发布时间】:2025-12-19 08:40:11
【问题描述】:

我遵循了关于从其他 SO 帖子构建静态哈希图的建议,但是现在当我尝试访问 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;
}

有什么想法吗?如果我试图拥有一组我可以访问的集合以检查字符串是否在该集合内的一个组中/它在哪个组中,是否有更好的方法来构建它?

【问题讨论】:

  • 你从不使用该字段。
  • 你在静态初始化器中隐藏了你的 EMGroups 变量。
  • 您有两个名为 EMGroups 的不同变量。一个是你永远不会在任何地方使用的类的静态成员,另一个是静态块的局部变量。在静态块中,局部变量会隐藏字段。
  • 我的错。我曾尝试使用一个临时的“aMap”,如*.com/questions/507602/… 中接受的答案所示。我在尝试运行它时遇到了一个 ExceptionInInitializerError,而在中间的某个地方我一定试图撤消工作并创建了副本。
  • 粘贴空指针异常堆栈。

标签: java static


【解决方案1】:
static{
    HashMap<String,TreeSet<String>> EMGroups = new HashMap<String, TreeSet<String>>();

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

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

虽然您实际上可以删除“EMUtil”。

【讨论】: