发布日期:2018-03-26
在JAVA中我怎么去比较字符串?+ 查看更多
在JAVA中我怎么去比较字符串?
+ 查看更多
发布日期:2018-03-10 11:56
分类:JAVA
浏览次数:133
我一直在我的程序里面使用 == 操作符来比较字符串。 然而,我遇到了一个bug,我就把其中一个放进 equals() ,然后这个bug 就好了。
== 到底好使不好使?啥时可以用?啥时不可用?它们的区别在哪里?
回答
== 是测试引用是否相同(不管它们是不是相同的对象)。
Equals() 是测试值是否相同(不管它们是不是逻辑上的“相等”)。
Objects.equals()* 会在调用 *.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 // ... but you should really just call Objects.equals() Objects.equals("test", new String("test")) // --> true Objects.equals(null, "test") // --> false你最好一直使用 Objects.equals() . 但是在一种特殊情况下,你可以使用 == 去比较,那就是你知道你在处理字符串池里的字符串时。