本文介绍了使用 ConcurrentHashMap 避免空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经被问过好几次了,但是我没有找到任何正确的答案.当您从 ConcurrentHashMap 获取结果时,如何避免抛出 NullPointerException.我有以下代码向我抛出 NullPointer.

I know this question has been asked several times, but I didn't find any right answer for the question. How do you avoid NullPointerException from being thrown when you fetch results from a ConcurrentHashMap. I have the below code that is throwing me a NullPointer.

public static String getPersonInfo(String personAddress) {
    //if(concMap!=null && concMap.containsKey(personAddress))       
    return concMap.get(personAddress);  
            //return null;  
}

在并发散列图中,我将人员 ID 和地址存储在并发散列图中.在少数情况下,id 为空.尽管我在将数据放入地图之前进行了空检查,但在尝试读取数据时仍然出现以下错误.

In the concurrent hashmap,I am storing person id and address in a concurrent hashmap. In a few cases, the id is null. Although I do a null check before putting the data in the map, I still get the below error while trying to read the data.

java.lang.NullPointerException
at java.util.concurrent.ConcurrentHashMap.get(Unknown Source)

有人请帮忙:(我已经浪费了 3 个多小时试图调试这个问题.虽然我在网上看到了很多帖子,但我还不是很清楚可以做些什么来避免它.

Someone please help :( I have wasted over 3 hours trying to debug this. Although I see a lot of posts online, I am not very clear yet with what can be done to avoid it.

推荐答案

对 personAddress 进行空检查,调用 get(null) 会抛出 NPE.它甚至在方法 文档

Do a null check on personAddress, calling get(null) throws a NPE.It's even specified in the method documentation

这篇关于使用 ConcurrentHashMap 避免空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 09:19