如何比较Java中的字符串? [英] How do I compare strings in Java?
问题描述
到目前为止,我一直在我的程序中使用 ==
运算符来比较我的所有字符串。
然而,我遇到了一个错误,将其中一个更改为 .equals()
而是修复了错误。
I've been using the ==
operator in my program to compare all my strings so far.
However, I ran into a bug, changed one of them into .equals()
instead, and it fixed the bug.
==
不好?什么时候应该不应该使用?有什么区别?
Is ==
bad? When should it and should it not be used? What's the difference?
推荐答案
==
测试参考相等(是否它们是同一个对象)。
==
tests for reference equality (whether they are the same object).
.equals()
测试值相等(它们在逻辑上是否相等 )。
.equals()
tests for value equality (whether they are logically "equal").
Objects.equals()在调用 null
> .equals()所以你不必(从JDK7开始,也可以在番石榴)。
Objects.equals() checks for null
before calling .equals()
so you don't have to (available as of JDK7, also available in Guava).
String.contentEquals()比较 String $ c的内容$ c>包含任何
CharSequence
的内容(自Java 1.5起可用)。
String.contentEquals() compares the content of the String
with the content of any CharSequence
(available since Java 1.5).
因此,如果你想测试两个字符串是否具有您可能想要使用的相同值 Objects.equals()
。
Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals()
.
// These two have the same value
new String("test").equals("test") // --> true
// ... but they are not the same object
new String("test") == "test" // --> false
// ... neither are these
new String("test") == new String("test") // --> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
"test" == "test" // --> true
// ... string literals are concatenated by the compiler
// and the results are interned.
"test" == "te" + "st" // --> true
// ... but you should really just call Objects.equals()
Objects.equals("test", new String("test")) // --> true
Objects.equals(null, "test") // --> false
Objects.equals(null, null) // --> true
您几乎始终想要使用对象.equals()
。在您知道的罕见情况下,您正在处理实习字符串,可以使用 ==
。
You almost always want to use Objects.equals()
. In the rare situation where you know you're dealing with interned strings, you can use ==
.
来自 JLS 3.10.5。 字符串文字 :
此外,字符串文字总是指相同类的实例
String
。这是因为字符串文字 - 或者更常见的是作为常量表达式值的字符串(§15.28) - 使用方法String.intern
进行实习,以便共享唯一的实例。
Moreover, a string literal always refers to the same instance of class
String
. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the methodString.intern
.
类似的例子也可以在 JLS 3.10.5-1 。
这篇关于如何比较Java中的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!