==测试引用是否相等(它们是否是同一对象)。
.equals()测试值是否相等(在逻辑上是否为“相等”)。
Objects.equals()null在调用之前进行检查,
.equals()因此您不必(在JDK7起可用,在Guava中也可用)。
因此,如果要测试两个字符串是否具有相同的值,则可能要使用Objects.equals()。
// These two have the same valuenew String("test").equals("test") // --> true // ... but they are not the same objectnew String("test") == "test" // --> false // ... neither are thesenew 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")) // --> trueObjects.equals(null, "test") // --> falseObjects.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检查留给了您。



