如何在Java中进行字符串(String)比较



一直以来我都是用“ ==” 操作符来比较字符串。但是,我遇到了一个错误,用 .equals() 替换了一个 == 操作符,错误就解决了。

== 是不好的咩? 到底应不应该用它? 用不用的区别是什么?

-----------------------------------------------------分割线-------------------------------------------------------------------------------------

票选答案一:

“==” 检验引用是否相同
.equals() 检验值是否相等

因此,如果你真的想要检验两个字符串是否有相等的值,那么你应该用 .equals() (除了少数情况下,你可以保证两个有相同的值的字符串将代表同一个对象 例如:字符串的留驻String interning)


“==”是用来检验两个字符串是否为同一个对象的

<span style="font-size:14px;">// 这两个有相同的值
new String("test").equals("test") // --> true 
// ... 但不是同一个对象
new String("test") == "test" // --> false // ... 这两个也不是
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 // concatenation of string literals happens at compile time,
// also resulting in the same object字符串连接发生在变异时,所以最终也是同一个对象
"test" == "te" + "st" // --> true// but .substring() is invoked at runtime, generating distinct objects但是 .substring()在运行时就被调用了,产生了不同的对象"test" == "!test".substring(1) // --> false// interned strings can also be recalled by calling .intern() interned strings也可以通过 .intern()调用 "test" == "!test".substring(1).intern() // --> true
</span>

需要注意的是 == 相比equals() 要略低级一些(只是一个简单的引用比较而不是一个方法调用),因此,在某些情况下可能适用。(例如 你可以确定你只是处理interned strings)它可以展现重要的性能改进。当然,这种情况也是比较少见的。





原文地址 http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值