-2

I have checked everywhere for a solution to this problem and simply cannot find one despite its apparent simplicity.

I keep getting a NullPointerException when calling myFunction():

private static Map<String, Map<String, Integer>> data;

public Class() {
    data = new Map<String, Map<String, Integer>();
}

public static void myFunction(String key, String val0, int val1) {
    boolean createNewEntry = false;
    if(null == data) {
        createNewEntry = true;
    }
    else if(!data.containsKey(key)) {
        createNewEntry = true;
    }
    if(createNewEntry) {
        data.put(key, new HashMap<String, Integer>()); // This throws a NullPointerException.
    }
    data.get(key).put(val0, data.get(key).get(val0) + val1);
}

The stack trace (with some project-specific data removed) is as follows:

Could not pass [Event] to [JAR file] v1.0.0
org.[parent].event.EventException
    ... (irrelevant)
Caused by: java.lang.NullPointerException
    at net.[package name].[class].myFunction([source file].java:93)
    at net.[package name].[class].otherFunction([source file].java(108)
    at net.[package name].[other class].anotherFunction([other file].java(65)
    at net.[package name].[main class].on[Event]([main file].java:97) ~[?:?]
    at sun.reflect.GeneratedMethodAccessor2.invoke(Unknown Source) ~[?:?]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:[versioning number]]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[?:[versioning number]]
    at org.[a different package name].plugin.java.JavaPluginLoader$1.execute([a file].java:301) ~[[versioning number]:[more data]]
    ... 15 more

Thank you in advance for any insight into this problem.

  • 1
    Well, after first null check you are sure that `data == null`. and then you just put entry into `map` that, you know for sure, is null. Why would you do that? – Random Guy May 20 '18 at 00:01
  • @RandomGuy The issue here is that the constructor, which _does_ initialize the map, is never being called. – Tim Biegeleisen May 20 '18 at 00:02

1 Answers1

1

You should be using a static block to initialize static variables:

public class yourClass {
    private static Map<String, Map<String, Integer>> data;

    static {
        data = new Map<String, Map<String, Integer>();
    }

    public static void myFunction(String key, String val0, int val1) {
        // ...
    }
}

While you do initialize the map in the constructor, this won't help because you never call the constructor.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Thank you! That error seems to be gone, but the next line (`data.get(key).put(val0, data.get(key).get(val0) + val1);`) is now throwing the same exception. What might be causing that? – public satanic void May 20 '18 at 00:10
  • Never mind, I figured out the error - the `.get(val0)` part was initially null. Thank you again for your quick reply! – public satanic void May 20 '18 at 00:13