将非空键和值放入哈希表时出现 NullPointerException

shr*_*est 3 java hashtable nullpointerexception

当 put() 的参数都不为 null 时,以下代码中会发生 java.util.Hashtable 的空指针异常:

import java.util.Hashtable;

interface action
{
   void method();
}

class forclass implements action
{
  public void method()
  {
    System.out.println("for(...){");
  }
}

class ifclass implements action
{
  public void method()
  {
    System.out.println("if(..){");
  }
}

public class trial
{
  static Hashtable<String,action> callfunc;
  //a hashtable variable
  public static void init()
  {
    //System.out.println("for"==null); //false
    //System.out.println(new forclass() == null); //false
    callfunc.put("for",new forclass()); //exception occuring here
    callfunc.put("if",new ifclass());
    //putting values into the hashtable
  }
  public static void main(String[] args)
  {
    init(); //to put stuff into hashtable
    action a = callfunc.get("for");
    //getting values for specified key in hashtable
    a.method();
    callfunc.get("if").method();
  }
}
Run Code Online (Sandbox Code Playgroud)

线程“main”中的异常 java.lang.NullPointerException -
at trial.init(trial.java:33)
at trial.main(trial.java:38)
为什么会发生此异常?我如何解决它?

Roh*_*ain 5

您尚未初始化您的Hashtable:-

static Hashtable<String,action> callfunc; // Reference points to null
Run Code Online (Sandbox Code Playgroud)

当 put() 的参数都不为空时

您应该使用HashMap, 这允许1 null key,以避免NPE在使用putwith时获取null key方法,在Hashtable抛出的情况下NPE,因为它不允许null keys, or value

因此,将您的声明更改为:-

static Hashtable<String,action> callfunc = new Hashtable<String, action>();
Run Code Online (Sandbox Code Playgroud)

甚至更好:-

static Map<String, action> callfunc = new HashMap<String, action>();
Run Code Online (Sandbox Code Playgroud)

作为旁注,您应该遵循Java Naming Convention您的代码。所有的类名和接口名,都应该以UpperCase字母开头,后面跟着CamelCasing