到目前为止,我一直在程序中使用==运算符来比较所有的字符串。 然而,我遇到了一个错误,将其中一个改为.equals(),它修复了这个错误。

==不好吗?什么时候应该使用,什么时候不应该使用?有什么不同?


当前回答

==执行引用相等性检查,2个对象(在本例中为字符串)是否引用内存中的同一对象。

equals()方法检查两个对象的内容或状态是否相同。

显然==更快,但如果你只是想知道2个字符串是否包含相同的文本,在许多情况下会(可能)给出错误的结果。

当然推荐使用equals()方法。

不要担心性能。使用String.equals()有以下几点值得鼓励:

Implementation of String.equals() first checks for reference equality (using ==), and if the 2 strings are the same by reference, no further calculation is performed! If the 2 string references are not the same, String.equals() will next check the lengths of the strings. This is also a fast operation because the String class stores the length of the string, no need to count the characters or code points. If the lengths differ, no further check is performed, we know they cannot be equal. Only if we got this far will the contents of the 2 strings be actually compared, and this will be a short-hand comparison: not all the characters will be compared, if we find a mismatching character (at the same position in the 2 strings), no further characters will be checked.

当一切都说了,做了,即使我们可以保证字符串是实习生,使用equals()方法仍然不是人们可能认为的开销,绝对是推荐的方式。如果您想要有效的引用检查,那么在语言规范和实现保证相同enum值将是相同对象(通过引用)的地方使用enum。

其他回答

是的,很糟糕……

==表示两个字符串引用是完全相同的对象。您可能听说过这种情况,因为Java保留了某种文字表(它确实如此),但情况并非总是如此。一些字符串以不同的方式加载,从其他字符串构造,等等,所以永远不要假设两个相同的字符串存储在相同的位置。

Equals为你做真正的比较。

==测试对象引用,.equals()测试字符串值。

有时,==看起来像是比较值,因为Java在幕后做了一些工作,以确保相同的内联字符串实际上是相同的对象。

例如:

String fooString1 = new String("foo");
String fooString2 = new String("foo");

// Evaluates to false
fooString1 == fooString2;

// Evaluates to true
fooString1.equals(fooString2);

// Evaluates to true, because Java uses the same object
"bar" == "bar";

但是要小心空值!

==可以处理空字符串,但从空字符串调用.equals()会导致异常:

String nullString1 = null;
String nullString2 = null;

// Evaluates to true
System.out.print(nullString1 == nullString2);

// Throws a NullPointerException
System.out.print(nullString1.equals(nullString2));

因此,如果您知道fooString1可能为空,请通过写入来告诉读取器

System.out.print(fooString1 != null && fooString1.equals("bar"));

下面是更短的,但不太明显,它检查null:

System.out.print("bar".equals(fooString1));  // "bar" is never null
System.out.print(Objects.equals(fooString1, "bar"));  // Java 7 required

是的,==不利于比较字符串(实际上是任何对象,除非您知道它们是规范的)。==只是比较对象引用。.equals()测试是否相等。对于字符串,它们通常是相同的,但正如你所发现的,这并不总是保证的。

我同意zacherates的回答。

但是你能做的是在非文字字符串上调用intern()。

来自zacherates的例子:

// ... but they are not the same object
new String("test") == "test" ==> false 

如果你实习非文字字符串相等为真:

new String("test").intern() == "test" ==> true 

操作符==总是用于对象引用比较,而String类.equals()方法用于内容比较被重写:

String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1 == s2); // It prints false (reference comparison)
System.out.println(s1.equals(s2)); // It prints true (content comparison)