一般来说,==比较的是值,而equal比较的是内容。
对于基本数据类型,只有==没有equal,比较的就是它的值;
对于对象来说,都继承于object类,其equal方法如下:可见传进去的是引用,比较的是引用的值,即内存里的地址值。
//obj the reference object with which to compare.
public boolean equals(Object obj) {
return (this == obj);
}
而对于String来说:先与传进去的引用比较地址;如果是String类的话,就一个一个字符串相比较。
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;
}
对于包装类如Integer,重写了equal方法,同样里面比较的是值
public boolean equals(Object obj) {
if (obj instanceof Integer) {
return value == ((Integer)obj).intValue();
}
return false;
}