java如何比较字符串,如何比较Java中的字符串?

小编典典

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

.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值