How do I check if two strings are equal in Java when either one of the strings can be a null?

huangapple go评论56阅读模式
英文:

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。否则比较s1s2。像这样,

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);
}

huangapple
  • 本文由 发表于 2020年9月18日 12:30:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63949355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定