简体   繁体   English

将非空键和值放入Hashtable时发生NullPointerException

[英]NullPointerException when putting a non-null key and value into a Hashtable

java.util.Hashtable's null pointer exception is occuring in the following code when neither of the arguments to put() are null : 当put()的两个参数都不为null时,以下代码中发生java.util.Hashtable的null指针异常:

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();
  }
}

Exception in thread "main" java.lang.NullPointerException - 线程“主”中的异常java.lang.NullPointerException-
at trial.init(trial.java:33) 在trial.init(trial.java:33)
at trial.main(trial.java:38) 在trial.main(trial.java:38)
why is this exception occuring? 为什么会发生这种异常? how do i fix it? 我如何解决它?

You have not initialized your Hashtable : - 您尚未初始化Hashtable :-

static Hashtable<String,action> callfunc; // Reference points to null

when neither of the arguments to put() are null 当put()的两个参数都不为null时

You should rather use HashMap , which allows 1 null key , to avoid getting NPE when using put with null key , method which in case of Hashtable throws NPE , because it does not allow null keys, or value . 您应该使用允许1 null key HashMap ,以避免在使用带null key put时获取NPE ,该方法在Hashtable情况下会抛出NPE ,因为它不允许null keys, or value

So, change your declaration to: - 因此,将您的声明更改为:-

static Hashtable<String,action> callfunc = new Hashtable<String, action>();

or even better: - 甚至更好:-

static Map<String, action> callfunc = new HashMap<String, action>();

As a side note, you should follow Java Naming Convention in your code. 附带说明,您应该在代码中遵循Java Naming Convention All the class name and interface name, should start with UpperCase letter, and follow CamelCasing thereafter. 所有的类名和接口名都应以UpperCase字母开头,然后跟随CamelCasing

callfunc reference is null not the inputs. callfunc reference为null而不是输入。

Try this: 尝试这个:

static Hashtable<String,action> callfunc = new Hashtable<String,action>()

Also this post might be useful as to whether you want Hashtable or HashMap 此外, 这篇文章对于您是否想要HashtableHashMap可能很有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM