String abc = "abc";
String abc2 = "abc";
String ab = "ab";
String c = "c";
String abc3 = ab + c;
System.out.println( abc );
System.out.println( abc2 );
System.out.println( abc3 );
System.out.println( abc == abc2 );
System.out.println( abc.equals( abc2 ) );
System.out.println( abc == abc3 );
System.out.println( abc.equals( abc3 ) );
打印的结果是:
abc
abc
abc
true
true
false
true
注意
System.out.println( abc == abc3 );
打印结果是false。
因为abc和abc2由于系统优化的某些原因,虽然定义了两个"abc",但是系统并不会分配两块空间分别存取"abc",而只是将后来的abc2指向abc所在的物理内存空间,加上==其实只是在比较对象所处的物理内存地址,所以结果是true。反过来,由于abc3是两块不同的物理内存空间上的值合并而成,所以abc和abc3所指向的物理内存空间地址是不一样的。
另外,equals方法是先按照==来判断,如果是true马上返回,如果不是则逐个字符进行比较。见下面的源码。
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;
}