# 问题
我之前一直用 == 操作符来比较两个字符串,但是,我遇到一个bug,最终,通过把 == 替换成 equals 进行修复的。
使用 == 哪里不对呢?到底什么时候用 == ?什么时候用 equals?它们有什么不同呢?
# 最佳答案
== 是测试引用是否相同,即判断它们是不是同一个对象。
String#equals ()
先来看一下它的源码实现:
直接使用双引号声明出来的String对象会直接存储在常量池中。
如果不是用双引号声明的String对象,可以使用String#intern()从字符串常量池中查询当前字符串是否存在?若不存在就会将当前字符串放入常量池中,再返回;如果存在就会直接返回当前字符串。
// 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) // --> trueString s1 = "testString";String s2 = new String("testString"); System.out.println(s1==s2.intern()); // trueString s3 = new String("testString"); System.out.println(s2.intern()==s3.intern());// true
今天的技能,你get到了吗?要不转发一波支持一下~~~
stackoverflow来源:https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java
往期推荐
?
- SO面试题13:如何便捷地将两个数组合到一起?
- Java中的文件锁到底是怎么回事?
- IDEA太强悍了,调试器竟然支持实时数据流分析啦,提前知道代码怎么跑的?
![cfd547e14440d4babbfcfc0e9aea7ca6.gif](https://img-blog.csdnimg.cn/img_convert/cfd547e14440d4babbfcfc0e9aea7ca6.gif)
点击