简体   繁体   中英

null check for hashmap key

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.]

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.

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.

caseChk coud be null try this

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

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

最好的选择是在调用toString()之前检查null。

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

Try this, this will work.

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

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