==
tests for reference equality (whether they are the same object).
(==
测试引用是否相等(它们是否是同一对象)。)
.equals()
tests for value equality (whether they are logically "equal").
(.equals()
测试值是否相等(在逻辑上是否相等)。)
Objects.equals() checks for null
before calling .equals()
so you don't have to (available as of JDK7, also available in Guava ).
(Objects.equals()在调用.equals()
之前检查是否为null
,因此您不必这样做(从JDK7开始可用,在Guava中也可用)。)
String.contentEquals() compares the content of the String
with the content of any CharSequence
(available since Java 1.5).
(String.contentEquals()将String
的内容与任何CharSequence
的内容进行比较(从Java 1.5开始可用)。)
Consequently, if you want to test whether two strings have the same value you will probably want to use Objects.equals()
.
(因此,如果要测试两个字符串是否具有相同的值,则可能要使用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
You almost always want to use Objects.equals()
.
(您几乎总是想使用Objects.equals()
。)
In the rare situation where you know you're dealing with interned strings, you can use ==
. (在极少数情况下,您知道要处理内部字符串, 可以使用==
。)
From JLS 3.10.5.
(从JLS 3.10.5起。)
String Literals : (字符串文字 :)
Moreover, a string literal always refers to the same instance of class String
.
(而且,字符串文字总是引用类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 method String.intern
. (这是因为使用方法String.intern
可以“ 插入 ”字符串文字(或更常见的是作为常量表达式的值的字符串(第15.28节 )),以共享唯一的实例。)
Similar examples can also be found in JLS 3.10.5-1 .
(在JLS 3.10.5-1中也可以找到类似的示例。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…