先来解释一下hashCode这个方法的作用: - (摘自JDK docs)
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
从注释上可以知道,hashCode可用于如Hashtable,HashMap这些集合对象,它通过hashCode对集合中的元素进行
散列处理,这样在查找时,通过hashCode可以很迅速的进行对象的查找操作。
However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
但是每位PG需要知道,如果不对Object的hashCode对象复写,则其它生成规则是根据内部的指针地址来算出hashCode。(这一点大家得特别注意)
下面是eclipse生成代码的一个示例:
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
它的问题就是,result中调用了 *super.hashCode()。*这么一来,同一个类被实例化多次后,虽然它们的名称都相同
但生成的hashCode都不同,当然在那些集合类中使用返回的也会有问题了。