==
测试引用相等性(它们是否是同一个对象)。
.equals()
值相等的测试(它们在逻辑上是否“相等”)。
Objects.equals()null
在调用之前检查,.equals()
所以你不必(从 JDK7 开始可用,在Guava 中也可用)。
因此,如果您想测试两个字符串是否具有相同的值,您可能需要使用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
您几乎总是想使用Objects.equals()
. 在您知道要处理内部字符串的极少数情况下,您可以使用.==
此外,字符串字面量始终引用class的同一个实例
String
。这是因为字符串文字 - 或者更一般地说,作为常量表达式(第15.28 节)的值的字符串- 被“嵌入”,以便使用方法共享唯一实例String.intern
。
类似的例子也可以在JLS 3.10.5-1 中找到。
其他需要考虑的方法
String.equalsIgnoreCase()忽略大小写的值相等。但是请注意,此方法在各种与语言环境相关的情况下可能会产生意外结果,请参阅此问题。
String.contentEquals()将 的内容String
与 any 的内容进行比较CharSequence
(自 Java 1.5 起可用)。使您不必在进行相等比较之前将 StringBuffer 等转换为 String,但将空值检查留给您。