hashCode和内存地址关系
1.当我们没有重写hashCode方法的时候默认的哈希值是内存地址是永远不相同的
Student s=new Student();
Student a=new Student();
System.out.println(s.hashCode());//2018699554
System.out.println(a.hashCode());//1311053135
这是没有重写hashCode的时候哈希值为默认的内存地址值
重写过后
Student s=new Student();
Student a=new Student();
System.out.println(s.hashCode());//29791
System.out.println(a.hashCode());//29791
哈希值是根据对应属性的内存地址来生成的
//重写的hashCode
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((sex == null) ? 0 : sex.hashCode());
return result;
}
//系统自带的hashCode(内存地址)
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;
}
return h;
}
上面的代码中name和sex就调用了对应的hashCode方法获取内存地址
hashCode去重复原理
哈希值是为了去重复用的
判断对象是否重复也是根据哈希值来进行判断的而不是通过内存地址
而哈希值的生成又和对象属性具体的值有关
所以生成一个对象就会生成一个哈希值(哈希值不是唯一的是根据属性的值来生成的)
但是有时候不同属性的值可能会生成同一个哈希值
所以在判断哈希值相同
后又调用重写的equals方法判断各个属性所对应的值是否相同如果相同代表重复不同则添加
如果连哈希值都不相同都不调用equals方法直接添加进去来节省时间提高效率