检查null时出现NullPointerException

Car*_*low -3 java map nullpointerexception

基本上,我创建了一个地图来存储一个唯一的键和一个项目列表.起初地图是null所以在我的类dosomething我检查地图是否为null但它返回一个异常.请参阅下面的代码.有谁知道我能做些什么来解决这个问题?

public class MyClass{
 private static Map<String, List<MyList>> MyMap = null;
 private static void doSomething(){
  String myKey = "hello";
  if(MyMap.get(myKey) == null ){ // Here is where i got the exception "java.lang.NullPointerException"
    //do something
  }
 }
}
public class MyList{
// do my List
}
Run Code Online (Sandbox Code Playgroud)

sti*_*ike 6

private static Map<String, List<MyList>> MyMap = null; // null here and not initialized

MyMap.get(myKey)
Run Code Online (Sandbox Code Playgroud)

你的MyMap为null所以它正在抛出NPE