我有ViewPartner
类
public class ViewPartner {
private int id;
private boolean enabled;
public ViewPartner(int id, boolean enabled) {
this.id = id;
this.enabled = enabled;
}
@Override
public boolean equals(Object o){
if(o instanceof ViewPartner){
return id == ((ViewPartner) o).id;
} else {
return false;
}
}
}
和包含以下方法的ViewPartnerContainer
类:
public class SelectedViewPartnerContainer {
private Map<Integer, List<ViewPartner>> cahcedPagePartnersMap;
private Set<ViewPartner> rawPartners;
//GET, SET ,Contructor and other methods
public Collection<ViewPartner> getRawPartners(Set<ViewPartner> partners){
for(ViewPartner vp : partners){
if(rawPartners.contains(vp)){
partners.add(vp);
}
}
return partners;
}
}
现在我有以下代码:
SelectedViewPartnerContainer c = new SelectedViewPartnerContainer();
Set<ViewPartner> partners = new HashSet<ViewPartner>();
List<ViewPartner> rawLst = new ArrayList<ViewPartner>();
for(int i = 40; i < 50; i++){
rawLst.add(new ViewPartner(i, false));
}
for(int i = 37; i < 42; i++){
partners.add(new ViewPartner(i, true));
}
//adding rawLst to the c's rawPartners property
ViewPartner p2 = new ViewPartner(40, false);
Collection<ViewPartner> co = c.getRawPartners(partners);
List<ViewPartner> co2 = new ArrayList(c.getRawPartners(partners));
co.contains(p2); //false
co2.contains(p2); //true
为什么contains方法之间存在差异?
答案 0 :(得分:2)
HashSet<ViewPartner>
无法正常运行,因为ViewPartner未实现hashCode()
。读取Object.equals API:通常需要在重写此方法时覆盖hashCode方法,以便维护hashCode方法的常规协定,该方法声明相等的对象必须具有相等的哈希代码。