我有,
String str1 = "StringA";
String str2 = "StringA";
现在,我愿意
(str1 == str2)
有时它与字符串不匹配并返回false
但str1.equals(str2)总是回来true
我在这里缺少什么?
我不能总是使用equals,因为我的String也可以为空。
谢谢!
==比较参考而不是内容
要比较字符串,您需要使用String#equals:
.equals(); //If you consider the case
.equalsIgnoreCase(); //If you not consider the case
==比较确切的值。所以它比较primitive值是否相同,
.equals()调用 的comparison方法objects,它将比较引用指向的实际对象。在字符串的情况下,它比较每个字符以查看它们是否为equal.
在这里阅读更多: