字符串的==和equals辨析
首先看 java中equals函数的源码:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
可见,equals首先会判断两个字符串是否“==”,但是“==”只是case1:表示两个字符串的存储地址相等,当我们只是想判断值相等时,也就是case2:两个字符串内所有元素一一对应,char值相同,那么就要用equals,它包含case1和case2.str1=“123”;
str3=new String (“123”);
——>str1!=str3;but str1.equals(str3)