1

I'm very new to Java. Trying to access a field in the HashMap observationMap, and am told there is a NullPointerException when I check if the HashMap contains the key. In particular, in the getEventSpeed() method.

.containsKey() should return NULL, so not clear how this line causes issue for the if statement?

Thank you for your help

public class IsDrivingObservation {

  private Map<String,String> observationMap;

  public String getEventSpeed() {
    if (observationMap.containsKey("eventSpeed")) {
      return observationMap.get("eventSpeed");
    }
    return "foo";
  }

  public void setEventSpeed(String speed) {
    observationMap.put("eventSpeed", speed);
  }

}
Xstian
  • 8,184
  • 10
  • 42
  • 72

1 Answers1

3

you never create the observationMap. Try this:

private Map<String,String> observationMap = new HashMap<>();

otherwise you will get the NPE in both of your methods. That depends on which method you call first.

nano_nano
  • 12,351
  • 8
  • 55
  • 83