equals()
首先需要清楚equals()的作用
在Java中,对象进行比较时,会用到==
和equals()
==
比较的是对象在内存中的地址,即是否在物理上相等
equals
默认和==
一样,比较对象的内存地址。
/**
* Object类的equals()方法
*/
public boolean equals(Object obj) {
return (this == obj);
}
但是可以通过重写,实现对象逻辑上的比较。
/**
* 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;
}
hashCode()
其次需要清楚hashCode()的作用
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {@link java.util.HashMap}.
*/
以上文字截取自Object
类的hashCode()
注释,它说明了hashCode()
返回对象的哈希值,而哈希值的设置是为了方便查找。
/**
* Object类的hashCode方法
* native说明该方法由其他语言(C/C++)实现
*/
public native int hashCode();
这里有一点需要注意:hashCode不同于内存地址
hashCode()
也可被重写。
/**
* String类重写的hasCode()
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;