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;
}
}
複製代碼