Java类HashCode说明以及派生类一些HashCode重写
程序员文章站
2024-03-26 09:14:41
...
散列码(hash code)是由对象导出的一个整形值。散列码是没有规律的。如果x和y是两个不同的对象,x.hashCode()与y,hashCode()基本上不回相同
String类使用下列算法计算散列码:这样会是散列码更加均匀
int hash = 0;
for (int i = 0 ; i<length() ; i++)
hash = 31 * hash + charAt(i);
下面我们看这个例子:
String s = "Ok";
String b = new String("Ok");
System.out.println("s.hashCode = " + s.hashCode() +"\nb.hashCode = " +b.hashCode());
结果为:
s.hashCode = 2556
b.hashCode = 2556
由此可见,字符串的散列码是由内容导出的。其他的引用类型是随机导出的。
boolean[] a = {true,true,false};
Employee employee = new Employee("张三", 50000, 1997, 5, 3);
Student student = new Student("Maria Morris", "computer science");
System.out.println(Objects.hash(employee));
System.out.println(Objects.hash(employee,student));
System.out.println(Arrays.hashCode(a));
118352493
924049720
1252180
对象类型建议每个都重写自己的hashCode方法,
public class Student extends Person {
private String major;
public Student(String name, String major) {
super(name);
this.major = major;
}
@Override
public int hashCode() {
return Objects.hash(this.getName(),major);
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return "a student maroring in" + major;
}
}