原创

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是值是否相同.

本文来自:java中字符串的比较-小码农,转载请保留本条链接,感谢!

温馨提示:
本文最后更新于 2021年01月29日,已超过 1,185 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我
正文到此结束
该篇文章的评论功能已被站长关闭
本文目录