说到hashcode和equals不的不想到集合类的SET,set能清楚重复的东西。
假如:
public class People {
private String fistName;
private String lastName;
People(String fname,String lname){
this.fistName = fname;
this.lastName = lname;
}
}
你在hashSet时想根据姓名相同的为条件来去掉重复的,重写OBJECT类的hashcode和equals一定要写对了。
public class People {
private String fistName;
private String lastName;
People(String fname,String lname){
this.fistName = fname;
this.lastName = lname;
}
public int hashCode(){
return this.fistName.hashCode()*this.lastName.hashCode();
}
public boolean equals(Object o){
if( o instanceof People){
People p = (People)o;
if(this.fistName.equals(p.fistName)&&this.lastName.equals(p.lastName)){
return true;
}else{
return false;
}
}else{
return false;
}
}
}
当你要对一个类做比较的时候你的实现接口compareable,实现方法public int compareTo(People o)