[英]Null pointer exception with static hashMap
public class arraylst
{
static HashMap<String,List<String>>hm;
public static void main(String[] args)
{
hm.put("2",Arrays.asList("a","b","c"));
}
}
I don't understand why this causes NullPointerException
. 我不明白为什么这会导致NullPointerException
。
Can someone please help me out? 有人可以帮我吗?
You need to set hm
: 您需要设置hm
:
hm = new HashMap<String, List<String>>();
before you use it. 在使用之前。
您需要将HashMap<String,List<String>>
放入您的(最初为空) hm
字段中。
采用
static HashMap<String, List<String>> hm = new HashMap<String, List<String>>();
Unlike primitive variables, the Classes should be explicitly initialized. 与原始变量不同,应明确初始化类。 So create an instance of HasMap. 因此,创建一个HasMap实例。
You are pointing to a reference which don't have a Object. 您指向的是没有对象的参考。 So you are trying to refer a Object which haven't yet created. 因此,您尝试引用尚未创建的对象。
So using the "new" key word create an Object to overcome the exception 因此,使用“新”关键字创建一个对象来克服异常
static HashMap<String,List<String>> hm = new HashMap<String,List<String>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.