HashCode最重要的因素:
1.无论何时,对同一个对象调用hashcode()都应该生成同样的值。
2.想要使用hashcode实用,必须速度快,并且有意义,也就是,它必须基于对象的内容生成散列码,散列码不必要是独一无二的,更应该关注的是速度,但是通过hashcode()和equals()这两个方法唯一确定对象的身份。
3.由于在生成桶的下标前,hashcode()还需要做进一步的处理,所以散列码的生成范围不重要,只要是int即可。
4.好的hashcode()应该产生分布均匀的散列码,如果散列码都集中在一块,那么hashmap或hashset在某些区域的负载会比较重,这样就不如均匀分布的散列码函数快
生成合理的HashCode()基本指导:
1.给int变量result赋予某个非零值的常量,如17
2.给对象内每个有意义的域f(每个可以做equals()操作的域)计算出一个int的散列码c
3.合并计算得到散列码
4.返回result
5检查hashcode()最后的生成结果,确保相同的对象有相同的散列码
public class CountedString {
private static List<String> created=new ArrayList<>();
private String s;
private int id=0;
public CountedString(String s) {
this.s = s;
created.add(s);
for (String s1:created){
if (s1.equals(s)){
id++;
}
}
}
@Override
public String toString() {
return "CountedString{" +
"s='" + s + '\'' +
", id=" + id +'\''+"hashcode():"+hashCode()+
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CountedString that = (CountedString) o;
return id == that.id &&
Objects.equals(s, that.s);
}
@Override
public int hashCode() {
int result=17;
result=result*37+s.hashCode();
result=result*37+id;
return result;
}
}
Equals()方法的5个条件:
1.自反性 对任意的x,x.equals(x) 一定true
2对称性
3传递性
4一致性
5对任何不是null的x,x.equals(null)一定返回false
默认比较的是内存地址,基本类型值