重写hashcode和equals

equals与hashcode间的关系是这样的:bash

一、若是两个对象相同(即用equals比较返回true),那么它们的hashCode值必定要相同;ide

二、若是两个对象的hashCode相同,它们并不必定相同(即用equals比较返回false)。ui

为何必需要重写hashcode方法,其实简单的说就是为了保证同一个对象,保证在equals相同的状况下hashcode值一定相同,若是重写了equals而未重写hashcode方法,可能就会出现两个没有关系的对象equals相同的(由于equals都是根据对象的特征进行重写的),但hashcode确实不相同的。this

@Data
public class ShopProductSpecValueDTO {
    private String id;

    private String productId;

    private String specId;

    private String specvalueId;

    private String createdBy;

    private Date dateCreated;

    private String updatedBy;

    private Date dateUpdated;

    public ShopProductSpecValueDTO(){
    }

    public ShopProductSpecValueDTO(String productId,String specId,String specvalueId){
        this.productId = productId;
        this.specId = specId;
        this.specvalueId=specvalueId;
    }

    @Override
    public int hashCode() {
        int result = id != null ? id.hashCode() : 0;
        result = 31 * result + (productId != null ? productId.hashCode() : 0);
        result = 31 * result + (specId != null ? specId.hashCode() : 0);
        result = 31 * result + (specvalueId != null ? specvalueId.hashCode() : 0);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null){
            return false;
        }
        if (this == obj){
            return true;
        }
        if (getClass() != obj.getClass()){
            return false;
        }
        ShopProductSpecValueDTO o = (ShopProductSpecValueDTO) obj;
        if (this.productId != null ? !this.productId.equals(o.productId) : o.productId != null) return false;
        if (this.specId != null ? !this.specId.equals(o.specId) : o.specId != null) return false;
        if (this.specvalueId != null ? !this.specvalueId.equals(o.specvalueId) : o.specvalueId != null) return false;
        return true;
    }

}
复制代码
相关文章
相关标签/搜索