java中字符串类型的比较

时间:2022-06-29 16:16:19

String类型的比较中使用 "==" 和使用 ".equals()"的区别:

"==" 比较两个字符串是不是相同的引用(是否是相同的对象)

".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