【发布时间】:2015-05-04 07:10:37
【问题描述】:
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 可能为空)。
str1 在什么情况下可以在return str1.equals(str2) ? COMPARE_EQUALS : COMPARE_DIFFERS; 中成为null(假设前两个 if 块涵盖了这种情况,当str1 为空时)?
【问题讨论】:
-
不能,但 Eclipse 不够聪明,无法分辨。
-
(另外,为什么不直接使用
Objects.equals?) -
不相关但是:第二个和第三个
if可以合并为一个:if (str1 == null || str2 == null) return COMPARE_DIFFERS; -
@blackOcean 不,equals 和 == 做不同的事情。我的意思是提问者的 整个方法 与
java.util.Objects.equals(Object, Object)完全相同(不要与java.lang.Object.equals(Object)混淆) -
@Eran,好像它被自动标记了。投票支持重新开放。