问题 在这段代码中,变量如何为空?


FindBugs抱怨 在Comparator.compareStrings(String,String)中可能不可行的分支上str1的可能空指针解除引用 在这个方法中:

private static int compareStrings(final String str1, final String str2) {
    if ((str1 == null) && (str2 == null)) {
        return COMPARE_ABSENT;
    }
    if ((str1 == null) && (str2 != null)) {
        return COMPARE_DIFFERS;
    }
    if ((str1 != null) && (str2 == null)) {
        return COMPARE_DIFFERS;
    }
    return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS;
}

在Eclipse中,我也在最后一行看到警告(str1 可能是null)。

在什么情况下可以 str1  是 null 在 return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS; (鉴于前两个if块覆盖了情况,何时 str1 一片空白) ?


6195
2018-05-04 07:10


起源

它不能,但Eclipse不够聪明。 - immibis
(另外,为什么不使用 Objects.equals?) - immibis
不相关但是:第二和第三 if 可以组合成一个: if (str1 == null || str2 == null) return COMPARE_DIFFERS; - a_horse_with_no_name
@blackOcean不,等于和==做不同的事情。我的意思是提问者的 整个方法 完全一样的事情 java.util.Objects.equals(Object, Object) (不要混淆 java.lang.Object.equals(Object)) - immibis
@Eran,似乎它以某种方式自动标记。投票重新开放。 - Sergei Tachenov


答案:


您可以通过重新排列if语句来避免警告:

private static int compareStrings(final String str1, final String str2) {
    if (str1 == null) {
        if (str2 == null)) {
            return COMPARE_ABSENT;
        } else {
            return COMPARE_DIFFERS;
        }
    } else {
        if (str2 == null)) {
            return COMPARE_DIFFERS;
        } else {
            return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS;
        }
    }
}

10
2018-05-04 07:15



return str1 == null? (str2 == null?COMPARE_ABSENT:COMPARE_DIFFERS):( str1.equals(str2)?COMPARE_EQUALS:COMPARE_DIFFERS); //更简短的答案 - Harry.Chen
@ Harry.Chen但它更具可读性吗?我想这是一个意见问题:) - Eran
为了可读,我同意! :) - Harry.Chen


在你打电话的地方 str1.equals(str2)str1  不能 是 null。您应该在该位置禁止此警告。


2
2018-05-04 07:13