boolean equals(Object anObject);
boolean contentEquals(CharSequence cs);
这两个方法都可以用来比较String对象内容序列的异同,但也存在差异。
最大的差别就是String的equals方法只有在另一个对象是String的情况下才可能返回true,
而contentEquals只要求另一个对象是CharSequence或其子类的对象
测试代码如下:
/**
* String的equals方法和contentEquals方法的比较
* @author FREEDOM
*
*/
public class StringTest {
public static void main(String[] args) {
String s1="123";
String s2=new String("123");
StringBuilder sb=new StringBuilder("123");
System.out.println(s1.equals(s2)); //true
System.out.println(s1.contentEquals(s2)); //true
System.out.println(s1.equals(sb)); //false
System.out.println(s1.contentEquals(sb)); //true
}
}
具体原因可以参考equals方法和contentEquals方法的源码:
//来自String源码
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;
}
//来自String源码
public boolean contentEquals(CharSequence cs) {
// Argument is a StringBuffer, StringBuilder
if (cs instanceof AbstractStringBuilder) {
if (cs instanceof StringBuffer) {
synchronized(cs) {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
} else {
return nonSyncContentEquals((AbstractStringBuilder)cs);
}
}
// Argument is a String
if (cs instanceof String) {
return equals(cs);
}
// Argument is a generic CharSequence
char v1[] = value;
int n = v1.length;
if (n != cs.length()) {
return false;
}
for (int i = 0; i < n; i++) {
if (v1[i] != cs.charAt(i)) {
return false;
}
}
return true;
}
}