优雅的方式来检查两个字符串是否不同

Can*_*ner -2 c# java string-comparison

是否有一种优雅的方式来比较两个Strings并检查它们是否不同?例如Java,我通常使用类似于此的东西:

if (text1 != text2 || (text1 != null && !text1.equals(text2))) {
    // Texts are different
}
Run Code Online (Sandbox Code Playgroud)

这是非常普遍的事情,我想知道可能有更好的方法.

编辑: 理想情况下,我想要一个适用于大多数常见面向对象语言的伪代码.

ass*_*ias 10

在Java 7+中,您可以使用Objects#equals:

if (!Objects.equals(text1, text2))
Run Code Online (Sandbox Code Playgroud)

在引擎盖下,它会执行与您的问题中的代码类似的操作:

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}
Run Code Online (Sandbox Code Playgroud)

请注意,您的代码在Java中是破坏的:在这种情况下它将返回false:

String text1 = "abc";
String text2 = new String("abc");
if (text1 != text2 || (text1 != null && !text1.equals(text2))) {
    System.out.println("Ooops, there is a bug");
}
Run Code Online (Sandbox Code Playgroud)

isNotEquals条件的正确方法是:

if (text1 != text2 && (text1 == null || !text1.equals(text2)))
Run Code Online (Sandbox Code Playgroud)