英文:
How do I check if two strings are equal in Java when either one of the strings can be a null?
问题
我有两个字符串...
String s1 = /* 任意字符串,可以为null */;
String s2 = /* 任意字符串,可以为null */;
我需要知道它们是否相等。
我不能使用s1.equals(s2)
,因为如果s1 == null
会导致空指针异常。
这是检查它们是否相等的最佳方法吗?
public boolean stringsAreEqual(String s1, String s2) {
boolean bEqual = false;
if ((s1 == null) && (s2 == null)) {
bEqual = true;
} else if ((s1 != null) && s1.equals(s2)) {
bEqual = true;
} else if ((s2 != null) && s2.equals(s1)) {
bEqual = true;
}
return bEqual;
}
英文:
I have two strings ...
String s1 = /* any string, could be null */;
String s2 = /* any string, could be null */;
I need to know if they are equal.
I can't do s1.equals(s2)
because NullPointer if s1 == null
.
Is this the best way to check if they are equal?
public boolean stringsAreEqual(String s1, String s2) {
boolean bEqual = false;
if ((s1 == null) && (s2 == null)) {
bEqual = true;
} else if ((s1 != null) && s1.equals(s2)) {
bEqual = true;
} else if ((s2 != null) && s2.equals(s1)) {
bEqual = true;
}
return bEqual;
}
答案1
得分: 10
你不需要为此创建新方法。你可以使用Java标准库中的java.util.Objects#equals(Object a, Object b)
。以下是JDK版本的定义。
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
英文:
You do not need to create a new method for that. You can use java.util.Objects#equals(Object a, Object b)
from the Java standard library. Below is the definition as on JDK.
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
答案2
得分: 1
你可以这样比较字符串。
这是Java内部代码使用的方法。
英文:
You can compare strings like this.
This is what Java internal code uses.
public boolean stringsAreEqual(String s1, String s2) {
return (s1 == null ? s2 == null : s1.equals(s2));
}
答案3
得分: 1
A == null ? B == null : A.equals(B)
英文:
A==null ? B==null : A.equals(B)
答案4
得分: 1
似乎你可以首先将方法设为static
,其次检查s1
是否为null
,如果是,则检查s2
是否为null
。否则比较s1
和s2
。像这样,
public static boolean stringsAreEqual(String s1, String s2) {
if (s1 == null) {
return s2 == null;
}
return s1.equals(s2);
}
英文:
It seems like you could first make the method static
, and second test if s1
is null
, if it is test s2
for null. Otherwise compare s1
and s2
. Like,
public static boolean stringsAreEqual(String s1, String s2) {
if (s1 == null) {
return s2 == null;
}
return s1.equals(s2);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论