首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >避免`hashmap`中的`toString`中的`NullPointerExceptions`

避免`hashmap`中的`toString`中的`NullPointerExceptions`
EN

Stack Overflow用户
提问于 2019-05-17 02:38:02
回答 1查看 84关注 0票数 -1

在一些试图与HashMap中的字符串进行比较的代码中,我尽量避免出现NullPointerException

HashMap定义得很好,但是在HashMap中可能有也可能没有相应的条目,所以我相信这可能是我的NPE和相关的Android Studio警告的来源。

我的代码是:

代码语言:javascript
复制
if (region_ids !=null && source_region != null && selected_id != null) {
    if (source_region.equals("it") && region_ids.containsKey("it") && !selected_id.equals(region_ids.get("it").toString())) {
        // Do stuff for mismatched region
    }
}

其中region_idsHashMap

我是否做了足够的工作来防止NullPointerException%s?

如果是这样,为什么Android Studio仍然在IDE中给我警告?

(请注意,故意包含Android-Studio标记是因为这个问题的最后部分很具体。)

更新

根据Code-Apprentice的评论和Nosyara的回答,我现在有以下两个if语句的变体,但仍然得到关于toString()方法的NPE警告:

代码语言:javascript
复制
if ( region_ids_string != null && spin_region_id != null && source_region != null && selected_id != null && assoc_ids != null) {
    if ( region_ids_string.size() > spin_region_id.getSelectedItemPosition()) {
        if (source_region.equals("com_mx") && assoc_ids.get("com_mx") != null && assoc_ids.containsKey("com_mx") && !selected_id.equals(assoc_ids.get("com_mx").toString())) {
                return true;
        } else if ("com_au".equals(source_region) && assoc_ids.containsKey("com_au") && assoc_ids.get("com_au") != null && !assoc_ids.get("com_au").toString().equals(selected_id)) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
} else {
    return false;
}

因此,我相信我现在正在检查null,"",以及Key是否存在于HashMap中,但仍然相信语句有可能生成NPE...

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-17 03:22:28

如果你把常量放在左边来反转条件,你会自动检查它是否有空值。如下所示:

代码语言:javascript
复制
if ("it".equals(source_region) && 
region_ids.containsKey("it") && 
!(region_ids.get("it").toString().equals(selected_id))) {
    // Do stuff for mismatched region
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56174726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档