一、"==" 与 equals
下边这段代码应该都看过或者写过:
String str1 = "test";
String str2 = "test";
String str3 = new String("test");
String str4 = new String("test");
System.out.println(str1 == str2);//true
System.out.println(str1.equals(str2));//true
System.out.println(str3 == str4);//false
System.out.println(str3.equals(str4));//true
由于 "==" 进行值比较,则在str1与str2比较为true,而在new String 的str3与str4为false,虽然equals进行的是引用比较,但String中将equals方法重写,来达到进行比较字符串中的值比较。
二、String中的equals
先看源码:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
源码注释中写道:Compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
翻译:将此字符串与指定的对象进行比较。当且仅当参数不为空并且是表示与此对象相同的字符序列的字符串对象时,结果为真。
看代码就是逐个对比两个字符串序列,比如下边图中红框内的判断条件:
1、while循环体内:当字符序列其中某个字符与比较字符不相同是返回false;
2、结束循环,对比结束无不相同的情况,返回true;