@Override
public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((product == null) ? 0 : product.hashCode());
// return result;
//自己手动手写hashCode,代码如下:
String buyitemid = product.hashCode() + "-";
//如果product里有样式
if(product.getStyles().size()>0){
buyitemid += product.getStyles().iterator().next().getId();
}
return buyitemid.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final BuyItem other = (BuyItem) obj;
if (product == null) {
if (other.product != null)
return false;
} else if (!product.equals(other.product))
return false;
//再手动添加一些判断条件
//如果一个product有样式,另一个product没有样式,则两个 BuyItem是不一样的
if(product.getStyles().size()!= other.product.getStyles().size()){
return false;
}
if(product.getStyles().size()>0){
ProductStyle style = product.getStyles().iterator().next();
ProductStyle otherstyle = other.product.getStyles().iterator().next();
//这里用equals就可以了,不需要用 == 号判断
if(!style.equals(otherstyle)){
return false;
}
}
return true;
}
hashcode() 和 equals()方法
最新推荐文章于 2021-10-21 19:09:49 发布