null check for hashmap key

2020-02-16 02:54发布

问题:

I have a scenario where I need to check for null. I have a key named dT:

String dT = (String) caseChk.get("dT");

This throws a NullPointerException, since that key itself doesn't exist. If I check with

if(caseChk.get("dT") != null) {
    // do something
}

yet another NullPointerException is thrown because of .get. How can I test for null when a key in the map doesn't exist? I understand that the put method should handle it, but that isn't under my control.]

回答1:

Even now I get nullpoiner since .get throws exception

If caseChk.get("dT") is only line you have there and sure it is throwing exception, then only possibility is caseChk could be null.



回答2:

To make sure key exists you should use HashMap#containsKey(key) function. Once key exists you may use HashMap#get(key) to get the value and compare it to null.



回答3:

caseChk coud be null try this

 String dT;
if(chaseChk!= null) 
dT= (String)caseChk.get("dT");`


回答4:

Try this using the method to check null

public String checkNull_HashMap(Hashtable hashMap, String hashKey) {

    if (hashMap.get(hashKey) == null) {
        return "";
    } else {
        return hashMap.get(hashKey).toString();
    }
}


回答5:

The best option is to check for null before calling toString()

if ( hashMap.get(hashKey) != null ) { return hashMap.get(hashKey).toString(); }


回答6:

Try this, this will work.

    if(!caseChk.isEmpty)
    {
      String dT = (caseChk.containsKey("dT")?(String)caseChk.get("dT"):" ")
    }