java 当两个字符串都可以为空时如何比较两个字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30081520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compare two Strings when both can be null?
提问by Benjy Kessler
I am aware that it is better to call the equals
method over using the ==
operator (see this question). I want two strings to compare as equal if they are both null or if they represent the same string. Unfortunately the equals
method will throw an NPE
if the strings are null
. My code is currently:
我知道最好equals
使用==
运算符调用该方法(请参阅此问题)。如果两个字符串都为 null 或者它们表示相同的字符串,我希望它们比较相等。不幸的是,如果字符串是 ,该equals
方法将抛出。我的代码目前是:NPE
null
boolean equals(String s1, String s2) {
if (s1 == null && s2 == null) {
return true;
}
if (s1 == null || s2 == null) {
return false;
}
return s1.equals(s2);
}
This is inelegant. What is the correct way to perform this test?
这是不雅的。执行此测试的正确方法是什么?
回答by fge
If Java 7+, use Objects.equals()
; its documentation explicitly specifies that:
如果 Java 7+,请使用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.
[...] 如果两个参数都为 null,则返回 true,如果只有一个参数为 null,则返回 false。否则,通过使用第一个参数的 equals 方法确定相等。
which is what you want.
这就是你想要的。
If you don't, your method can be rewritten to:
如果不这样做,您的方法可以重写为:
return s1 == null ? s2 == null : s1.equals(s2);
This works because the .equals()
contract guarantees that for any object o
, o.equals(null)
is always false.
这是有效的,因为.equals()
合约保证对于任何对象o
, ,o.equals(null)
总是假的。
回答by Alex Salauyou
From Objects.equals()
:
return (a == b) || (a != null && a.equals(b));
Very simple, self-explaining and elegant.
非常简单,不言自明和优雅。
回答by Michal Kordas
If you can't use Java 7+ solution, but you have Guava or Commons Lang in classpath, then you can use the following:
如果您不能使用 Java 7+ 解决方案,但您在类路径中有 Guava 或 Commons Lang,那么您可以使用以下内容:
Guava:
番石榴:
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();
or
或者
import org.apache.commons.lang3.StringUtils;
StringUtils.equals(s1, s2);