Java .containsKey() 方法是否返回空指针异常?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21129481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:47:34  来源:igfitidea点击:

Does the .containsKey() method return null pointer exception?

javahashmap

提问by Bharath Naidu

I have a hashmap and I need to check if a certain value is present as a key in the hashmap. The problem is the first time I need to perform the check, the hashmap can be empty or null. Will the .containsKey() do the job of returning false if the hashmap is null or empty in this case or should I add an additional null pointer check?

我有一个哈希图,我需要检查某个值是否作为哈希图中的键存在。问题是我第一次需要执行检查时,hashmap 可以为空或为空。如果在这种情况下 hashmap 为 null 或为空, .containsKey() 是否会执行返回 false 的工作,或者我应该添加额外的空指针检查吗?

Map<String, String> groupNameMap = new LinkedHashMap<String, String>();
if(abc!= null && !groupNameMap.containsKey(abc)){
        usersGroupName = getGroupName(abc,xyz,oci);


        }

Will this piece of code solve the problem? the groupNameMap can be either empty or null.

这段代码能解决问题吗?groupNameMap 可以为空或 null。

采纳答案by Aniket Thakur

Map<String, String> groupNameMap = new LinkedHashMap<String, String>();

Since you are creating the instance of the Map before calling containsKey() on it, no NPE will occur.

由于您是在调用 containsKey() 之前创建 Map 的实例,因此不会发生 NPE。

groupNameMapcannot be null by your piece of code.

groupNameMap您的代码不能为空。

回答by afpro

if groupNameMapcould be null, check it.

如果groupNameMap可能为空,请检查它。

and, you don't need check whether key abcis nullor not, nullis a valid key in Map

并且,你不需要检查按键是否 abcnull或不是,null是一个有效的关键Map