当两个字符串都可以为空时如何比较两个字符串?

How to compare two Strings when both can be null?

我知道调用 equals 方法比使用 == 运算符更好(参见 this question)。如果两个字符串都为 null 或者它们代表相同的字符串,我希望两个字符串比较相等。不幸的是,如果字符串是 nullequals 方法将抛出一个 NPE。我的代码目前是:

boolean equals(String s1, String s2) {
  if (s1 == null && s2 == null) {
    return true;
  }
  if (s1 == null || s2 == null) {
    return false;
  }
  return s1.equals(s2);
}

这很不雅。执行此测试的正确方法是什么?

来自Objects.equals()

return (a == b) || (a != null && a.equals(b));

非常简单、不言自明且优雅。

如果Java7+,使用Objects.equals();它的文档明确指出:

[...] if both arguments are null, true is returned and if exactly one argument is null, false is returned. Otherwise, equality is determined by using the equals method of the first argument.

这就是你想要的。

如果你不这样做,你的方法可以重写为:

return s1 == null ? s2 == null : s1.equals(s2);

这是可行的,因为 .equals() 合约保证对于任何对象 oo.equals(null) 始终为假。

如果你不能使用Java 7+解决方案,但你的类路径中有Guava或Commons Lang,那么你可以使用以下方法:

番石榴:

import com.google.common.base.Objects;

Objects.equal(s1, s2);

Commons Lang:

import org.apache.commons.lang3.builder.EqualsBuilder;

new EqualsBuilder().append(s1, s2).isEquals();

import org.apache.commons.lang3.StringUtils;

StringUtils.equals(s1, s2);