小编典典
== 测试引用是否相等(它们是否是同一对象)。
.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()。在极少数情况下,您知道要处理实习生字符串,可以使用==。
从JLS 3.10.5起。字符串文字:
而且,字符串文字总是引用class的相同实例String。这是因为使用方法将字符串文字(或更广泛地说,是常量表达式的值的字符串(第15.28节))“插入”以便共享唯一的实例String.intern。
在JLS 3.10.5-1中也可以找到类似的示例。
其他要考虑的方法
忽略大小写的String.equalsIgnoreCase()值相等。
String.contentEquals()比较的内容和String任何内容CharSequence(从Java 1.5开始可用)。使您不必在进行相等比较之前将StringBuffer等转换为String,但是将null检查留给了您。
2020-11-18