小码农 猫的一生在打哈欠中度过

java中字符串的比较

Q:java中==跟equals比较字符串为啥不同?

A:这些例子足够证明了


// 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

所以java中请使用equals来比较字符串,而不是使用==

==测试对象引用是否相同,而equals是值是否相同.

赏
支付宝赞赏码
支付宝
微信赞赏码
微信
分享 微博 QQ 空间 豆瓣 Twitter

本文最后更新于 2021 年 01 月 29 日,距今日已 2113 天。

签 java equals

本文出自 小码农,转载请注明出处。

此篇已闭评。

卷首