Java Collection框架在Collection的生命周期中需要基于不变字段的equals()和hashCode()方法
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;
public class CollectionRun {
public static void main(String[] args){
Set set=new HashSet();
Person p=new Person();
set.add(p);
System.out.println(set.contains(p));
p.setId("T");
System.out.println(set.contains(p));
}
}
class Person{
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public boolean equals(Object o) {
// TODO Auto-generated method stub
if (this == o) return true;
if (o == null || !(o instanceof Person))
return false;
Person other = (Person)o;
// unsaved objects are never equal
if (id == null || other.getId() == null)
return false;
return id.equals(other.getId());
}
//将hashCode这个方法过行注释和不注释时运行的两种结果,考虑一下为什么?
public int hashCode() {
if (id != null) {
return id.hashCode();
} else {
return super.hashCode();
}
}
}