1.使用toString 和equals 方法之前,注意看他们的类中是否重写了这两个方法,没有的话继承Object类
2.Object类中,equals 和==就是比较当前对象与比较对象的地址值;toString 就是:类名@地址值
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public boolean equals(Object obj) {
return (this == obj);
}
3.String类中 重写了上述方法,equals 先比较是否为同一对象(true),然后是否是当前对象的实例(true,遍历比较字符数组内容);
public String toString() {
return this;
}
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;
}
4.为了安全,重写equals(),时就必须重写hashCode(),