首页 > 解决方案 > jdk 1.8 String.equalsIgnoreCase 中的重复空检查

问题描述

String.equalsIgnoreCase 实现如下(Oracle JavaSE 1.8)

public boolean equalsIgnoreCase(String anotherString) {
    return (this == anotherString) ? true
            : (anotherString != null)
            && (anotherString.value.length == value.length)
            && regionMatches(true, 0, anotherString, 0, value.length);
}

我想知道是否(anotherString != null)有必要进行检查,因为this != anotherString已经表明它anotherString不为空。

标签: javastringnullpointerexceptionconditional-statements

解决方案


让我们假设你是对的,看看我们打电话时会发生什么equalsIgnoreCase(null)

  1. this == anotherString是假的;
  2. anotherString.value.length == value.length- 我们正在获得一个 NPE anotherString.value

因此,anotherString != null这里是必要和关键的。


this != anotherString已经表明anotherString不是null

不,它没有。它只能说明是否thisanotherString不相等。

例如,两者this != nullthis != "test"return true


推荐阅读