object本身的hashcode方法将对象内部地址转化为整数作为HashCode。
这主要是因为object的equals()方法比较的正是内存地址,为了保证当A.equals(B)时也有A.hashcode=B.hashcode(),故有这样的策略。
在不覆盖默认方法的前提下,同时创建两个相同对象时,hashcode是不一样的。这样在处理hashtable时用object作为key时就会很麻烦。
java自己包装的object比如string这些都重写了equals方法和hashcode方法,不再是用对象内部地址转化为整数,而是保证两个相同对象的hashcode是一致的。
string的hashcode方法为
Integer的hashcode方法为
为了方便做hash时的便利,我们自己建立新对象时也建议重写equals方法和hashcode方法(个人倾向于同时改写,以符合当A.equals(B)时也有A.hashcode=B.hashcode()这个逻辑)。当然从效率出发,如何设计一个hashcode方法避免散列冲突就是另外一个难题,就不在本文的讨论范围内了。
这主要是因为object的equals()方法比较的正是内存地址,为了保证当A.equals(B)时也有A.hashcode=B.hashcode(),故有这样的策略。
在不覆盖默认方法的前提下,同时创建两个相同对象时,hashcode是不一样的。这样在处理hashtable时用object作为key时就会很麻烦。
java自己包装的object比如string这些都重写了equals方法和hashcode方法,不再是用对象内部地址转化为整数,而是保证两个相同对象的hashcode是一致的。
string的hashcode方法为
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Integer的hashcode方法为
public int hashCode() {
return value;
}
为了方便做hash时的便利,我们自己建立新对象时也建议重写equals方法和hashcode方法(个人倾向于同时改写,以符合当A.equals(B)时也有A.hashcode=B.hashcode()这个逻辑)。当然从效率出发,如何设计一个hashcode方法避免散列冲突就是另外一个难题,就不在本文的讨论范围内了。