简体   繁体   English

如何在2个哈希图中初始化值

[英]How to initialize value within 2 hashmaps

I have a hashmap within another hashmap and I'm trying to access that data, but I'm getting NUllPointerExceptions. 我在另一个哈希图中包含一个哈希图,并且试图访问该数据,但是却遇到了NUllPointerExceptions。 My code goes like this: 我的代码是这样的:

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);

I get a NullException on the line if(!D.get(index).B.contains(key)) . 我在if(!D.get(index).B.contains(key))的行上得到NullException。 I'm guessing it's because of the List<String> . 我猜是因为List<String> How do I fix this? 我该如何解决?

if(!D.get(index).B.contains(key)) ,NPE由D.get(index).B引起,检查D.get(index)是否为null。

The problem could be with the D.get(index) part of it. 问题可能出在它的D.get(index)部分。 If index is not a proper key for D, then it will return null, and then you're trying to perform something with null, which is throwing the error. 如果index不是D的适当键,则它将返回null,然后您尝试使用null进行操作,这将引发错误。 Consider a try/catch instead. 考虑尝试/捕获。

Try this code 试试这个代码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM