如果不覆盖hashCode方法,会导致两个equals相等的实例,比如p1和p2,具有不相等的散列码,违反了hashCode的云顶。因此。add方法会把两个对象都添加到set中。
Object规范:
相等的对象,必须具有相等的散列码。
package com.rudd.io;
/**
* Created by 67534 on 2019/3/27.
*/
public class Person {
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public boolean equals(Object obj){
if(obj instanceof Person){
Person person = (Person)obj;
if(person.getName() != null && person.getAge() != null){
if(person.getName().equals(this.name) && person.getAge().equals(this.age)){
return true;
}
}
return false;
}
return false;
}
public Person(String name,Integer age){
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
return this.name.hashCode()+this.getAge();
}
}
Person p1 = new Person("zxm",28);
Person p2 = new Person("zxm",28);
System.out.println(p1.equals(p2));
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
Map<Person,Integer> map = new HashMap<Person, Integer>();
map.put(p1,1);
System.out.println(map.containsKey(p2));
map.put(p2,2);
一个好的散列函数通常倾向于“为不相等的对象产生不相等的散列码”
对象中的关键域,equals方法涉及到的每个域。如上的name和age:
类型 | hashCode计算方法 |
boolean | (f ? 1:0) |
byte,char,short,int | (inf)f |
long | (int)(f^(f>>>32)) |
float | Float.floatToIntBits(f) |
double | Double.doubleToLongBits(f) |