尝试在空对象引用上调用虚拟方法“boolean java.util.ArrayList.add(java.lang.Object)”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27100895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
提问by user3290805
I am trying to build new hashmap with arraylist from old hashmap, but I get this error
我正在尝试使用来自旧哈希图的数组列表构建新的哈希图,但出现此错误
Error:
错误:
ava.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
I know it is error with some initialisation but can not catch it
我知道某些初始化是错误的,但无法捕获它
code
代码
nMap = new HashMap<String, ArrayList<Integer>>();
for (String type: allTypes) {
if (oData.get(type).size() > 0) {
arraySort(oData.get(type));
nData.get(type).add(fData.get(type).get(0).value);
}
}
OData is old hashmap that contains data for sure...
OData 是旧的哈希图,它肯定包含数据......
回答by Naman Gala
You can use below code.
您可以使用以下代码。
if (nData.get(type) == null) {
nData.put(type, new ArrayList<>());
}
nData.get(type).add(fData.get(type).get(0).value);