hashcode() 和 equals()方法

@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;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值