在Java中,hashCode()方法用于生成一个整数散列值,该值通常用于散列数据结构(如HashMap,HashSet等)中
public class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + id;
result = 31 * result + (name == null ? 0 : name.hashCode());
return result;
}
}
Person person1 = new Person(1, "Alice");
Person person2 = new Person(2, "Bob");
Person person3 = new Person(1, "Alice");
import java.util.Objects;
public class TestHashCode {
public static void main(String[] args) {
int[] hashes = new int[3];
hashes[0] = Objects.hash(person1);
hashes[1] = Objects.hash(person2);
hashes[2] = Objects.hash(person3);
for (int i = 0; i < hashes.length; i++) {
System.out.println("hashes[" + i + "] = " + hashes[i]);
}
}
}
注意:如果两个对象根据equals()方法是相等的,那么它们的hashCode()方法必须产生相同的值。但是,如果两个对象根据equals()方法是不相等的,它们的hashCode()方法不一定要产生不同的值。然而,产生不同值的hashCode()方法可以提高散列数据结构的性能。