【问题标题】:Why does Android Studio give a Null Pointer Exception warning with this code?为什么 Android Studio 会使用此代码给出空指针异常警告?
【发布时间】:2019-06-09 20:23:53
【问题描述】:

我在 Android Studio 中有以下代码,但我收到Method invocation 'toString()' may produce 'NullPointerException' 的警告。

String source_regions_user_id = "";
if (user_ids != null && "".equals(source_region) && user_ids.containsKey(source_region) && user_ids.get(source_region) != null && user_ids.get(source_region) != "") {
    source_regions_user_id = user_ids.get(source_region).toString();
} else {
    return true; // Unable to find a matching user_id for source_region
}

请注意,user_idsHashmapsource_regionString

我相信我正在检查 toString() 所依赖的所有内容中的空值,那么为什么 Android Studio 仍会发出此警告?

【问题讨论】:

  • source_region 的值是多少?最后一部分似乎不正确user_ids.get(source_region) != ""将其更改为之前的检查!"".equals(user_ids.get(source_region))
  • @YCF_L 我会将其更改为! user_ids.get(source_region).isEmpty(),或者如果您不喜欢!isEmpty() 之间的“距离”,请使用user_ids.get(source_region).length() != 0
  • @Andreas 如果user_ids.get(source_region) 返回 null 怎么办?但你可以告诉我已经检查过user_ids.get(source_region) != null :) 好点
  • user_ids.containsKey(source_region) 是多余的,因为如果user_ids.get(source_region) != null 为真,那么containsKey 也为真。 --- "".equals(source_region) ?!?您确定吗?你没有错过!,是吗?此外,考虑到地图不会(可能)包含"" 作为键,检查不是多余的吗?
  • @YCF_L 不,第二条评论是针对 OP 的。

标签: java android-studio nullpointerexception


【解决方案1】:

编译器应该能够看到您检查是否为 null,但在 if 语句中许多条件,因此它可能超出了编译器性能的某个阈值。

由于else 只不过是return,因此您应该翻转语句。这消除了单独声明变量的需要。

我也将条件分开来评论它们。

if (user_ids == null)
    return true;
if (! "".equals(source_region)) // I think you meant the opposite check
    return true;
if (! user_ids.containsKey(source_region)) // Redundant, the next check will cover this
    return true;
if (user_ids.get(source_region) == null)
    return true;
if (user_ids.get(source_region) == "") // Object is not a string, so this will always fail
    return true;
String source_regions_user_id = user_ids.get(source_region).toString();

您还应该使用isEmpty()length() 来检查空字符串,而不是与"" 进行比较。

因此,考虑到这些 cmets,我们可以将代码更改为:

if (user_ids == null || source_region.isEmpty())
    return true;
Object obj = user_ids.get(source_region);
if (obj == null)
    return true;
String source_regions_user_id = obj.toString();
if (source_regions_user_id.isEmpty())
    return true;
// use value here

使用此代码,编译器不会感到困惑,因此不会发出警告,并且您只需在地图中查找一次。

【讨论】:

  • 谢谢,我会尝试将此信息整合到一个完整的解决方案中,并在我尝试后更新。
  • 将 hashmap.get() 的结果分配给 Object,然后检查该对象是否有 null 并使用带有 toString() 的对象似乎可以解决问题。
猜你喜欢
  • 2012-12-22
  • 1970-01-01
  • 2013-09-06
  • 1970-01-01
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
相关资源
最近更新 更多