简体   繁体   中英

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. 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)) . I'm guessing it's because of the 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. 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. 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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