计算机应用实践之--重写Java对象HashCode

2017-12-15  本文已影响0人  献计献策

我们系统有一个场景,根据我们业务自己定义的商家拆分规则,将用户提交的发票申请拆分成多个发票(运费、订单实收),重写hashCode的原因还是因为我们用到了HashMap这个数据结构。
将拆分规则作为Key,用户的订单列表作为Value用来计算总金额。
下面是代码重写equals()方法就会去重写hashCode计算。
参考 wiki hashcode链接

@Getter
@Setter
public class ApplicationSplitRule  implements Serializable{
    private Long id ;
    private String splitRuleName;//拆分规则名称
    private Integer supplyTypeId;//支持类型
    private String supplyTypeName;//支持类型名称
    private String vendorGroupIdList;//商家分组ID列表
    private String vendorGroupNameList;//商家分组名称列表
    private Integer invoiceAmountSource;//金额来源  运费,订单实收

    @Override
    public int hashCode() {
        int hash = 1;//选点质数 
        hash = hash * 13 + getId().hashCode();
        hash = hash * 17 + getSupplyTypeId().hashCode();
        hash = hash * 23 + getVendorGroupIdList().hashCode();
        hash = hash * 31 + getInvoiceAmountSource().hashCode();
        return hash;
    }

    @Override
    public boolean equals(Object obj) {
        if(this == obj){
            return  true;
        }
        if(obj instanceof ApplicationSplitRule){
            ApplicationSplitRule rule = (ApplicationSplitRule) obj;
            if (this.getId().equals(rule.getId())
                    &&this.getSupplyTypeId().equals(rule.getSupplyTypeId())
                    &&this.getVendorGroupIdList().equals(rule.getVendorGroupIdList())
                    && this.getInvoiceAmountSource().equals(rule.getInvoiceAmountSource())) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读