简体   繁体   中英

NullPointerException when checking null

Basically, I create a map to store a unique key and a list of items. at first the map is null so in my class dosomething im checking if the map is null but it returns an exception. Please see code below. Does anyone know what i can do to fix this issue?

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
}
private static Map<String, List<MyList>> MyMap = null; // null here and not initialized

MyMap.get(myKey)

your MyMap is null so it is throwing NPE

Your MyMap is null. Do as below..

 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
    }

Your MyMap is throwing the NullPointerException. This happens because you've explicitly set it to null:

private static Map<String, List<MyList>> MyMap = null;

Instead you should initialise MyMap first:

private static Map<String, List<MyList>> MyMap = new HashMap<String, List<MyList>>();

you have to initialize your HasMap.

Map<String, List<String>> myMap = new HashMap<String, List<String>>();
    if(myMap.get("bla") == null){
    //do somethig
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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