Java HashMap.put使用" new"抛出NullPointerException。关键词

时间:2018-05-19 23:52:37

标签: java object nullpointerexception null hashmap

我已经到处检查了这个问题的解决方案,尽管它显而易见,但却找不到一个。

我在致电NullPointerException时不断收到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);
}

堆栈跟踪(删除了一些项目特定数据)如下:

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

提前感谢您对此问题的任何见解。

1 个答案:

答案 0 :(得分:1)

您应该使用static块来初始化静态变量:

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) {
        // ...
    }
}

当您在构造函数中初始化地图时,这将无济于事,因为您从不调用构造函数。