[英]How to initialize value within 2 hashmaps
我在另一个哈希图中包含一个哈希图,并且试图访问该数据,但是却遇到了NUllPointerExceptions。 我的代码是这样的:
public class A {
ConcurrentHashMap<String, List<String>> B;
int data;
public A() {
B = new ConcurrentHashMap<String, List<String>>();
data = 0;
}
}
public class C {
ConcurrentHashMap<String, A> D;
....
D = new ConcurrentHashMap<String, A>();
....
D.put(someKey, new A());
....
if(!D.get(index).B.contains(key)) {
D.get(index).B.put(key, new ArrayList<String>());
}
D.get(index).B.get(key).add(value);
我在if(!D.get(index).B.contains(key))
的行上得到NullException。 我猜是因为List<String>
。 我该如何解决?
在if(!D.get(index).B.contains(key))
,NPE由D.get(index).B
引起,检查D.get(index)
是否为null。
问题可能出在它的D.get(index)部分。 如果index不是D的适当键,则它将返回null,然后您尝试使用null进行操作,这将引发错误。 考虑尝试/捕获。
试试这个代码
D = new ConcurrentHashMap<String, A>();
D.put(someKey, new A());
A aObj = D.get(index);
if (aObj != null) {
if (!aObj.B.contains(key)) {
aObj.B.put(key, new ArrayList<String>());
}
aObj.B.get(key).add(value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.