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

来源:互联网 发布:足球网站关注软件 编辑:程序博客网 时间:2024/05/16 19:51


一直以来我都是用“ ==” 操作符来比较字符串。但是,我遇到了一个错误,用 .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



0 0
原创粉丝点击