广告位
如何比较对比Java中的字符串相等?
作者: 分类:编程技术浏览(1,390)2021-7-5

问题:

==到目前为止,我一直在我的程序中使用运算符来比较我的所有字符串。但是,我遇到了一个错误,将其中一个.equals()改为,并修复了该错误。

==坏?什么时候应该使用,什么时候不应该使用?有什么不同?

回答:

== 测试引用相等性(它们是否是同一个对象)。

.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与 any 的内容进行比较CharSequence(自 1.5 起可用)。使您不必在进行相等比较之前将 StringBuffer 等转换为 String,但将空值检查留给您。

图片压缩在线工具 tools online