基本上,我创建了一个地图来存储唯一键和项目列表。起初地图是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
}
答案 0 :(得分:6)
private static Map<String, List<MyList>> MyMap = null; // null here and not initialized
MyMap.get(myKey)
你的MyMap为null所以它正在抛出NPE
答案 1 :(得分:2)
您的MyMap为空。请执行以下操作..
public class MyClass{
private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>(); // creating instance
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
}
答案 2 :(得分:1)
您的MyMap正在抛出NullPointerException。这是因为您已将其明确设置为null:
private static Map<String, List<MyList>> MyMap = null;
相反,您应首先初始化MyMap:
private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>();
答案 3 :(得分:0)
你必须初始化你的HasMap。
Map<String, List<String>> myMap = new HashMap<String, List<String>>();
if(myMap.get("bla") == null){
//do somethig
}