对Java字符串使用'=='而不是.equals [英] Using '==' instead of .equals for Java strings
问题描述
我知道这是之前的问题,但是尽管建议使用 .equals()
而不是 ==
比较运算符,我发现 ==
始终有效:
I know this has been asked before, but in spite of recommendations to use .equals()
instead of the ==
comparison operator, I found that ==
works all the time:
String s1 = "Hello";
String s2 = "Hello";
System.out.println(s1 == s2); // true
任何人都可以给我一个的例子==
运算符失败?
Can anyone give me an example of the ==
operator failing?
推荐答案
这是因为你很幸运。 Java中的 ==
运算符检查引用相等:如果指针相同,则返回true。它不检查内容是否相等。在编译时找到的相同字符串将折叠为单个 String
实例,因此它适用于 String
文字,但不能使用在运行时生成的字符串。
This is because you're lucky. The ==
operator in Java checks for reference equality: it returns true if the pointers are the same. It does not check for contents equality. Identical strings found at compile-time are collapsed into a single String
instance, so it works with String
literals, but not with strings generated at runtime.
例如,Foo==Foo
可能有效,但Foo== new String(Foo)
不会,因为 new String(Foo)
创建一个新的 String
实例,并打破任何可能的指针相等。
For instance, "Foo" == "Foo"
might work, but "Foo" == new String("Foo")
won't, because new String("Foo")
creates a new String
instance, and breaks any possible pointer equality.
更重要的是,大多数 在实际程序中处理的字符串
是运行时生成的。文本框中的用户输入是运行时生成的。通过套接字接收的消息是运行时生成的。从文件读取的东西是运行时生成的。因此,如果要检查是否使用等于
方法,而不是 ==
运算符,这一点非常重要内容平等。
More importantly, most Strings
you deal with in a real-world program are runtime-generated. User input in text boxes is runtime-generated. Messages received through a socket are runtime-generated. Stuff read from a file is runtime-generated. So it's very important that you use the equals
method, and not the ==
operator, if you want to check for contents equality.
这篇关于对Java字符串使用'=='而不是.equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!