当 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();
}
}
线程“main”中的异常 java.lang.NullPointerException -
在 trial.init(trial.java:33)
at trial.main(trial.java:38)
为什么会发生这个异常?我如何解决它?