I have overrided the equals method of a java object. (actually the objects in kotlin but its easily understood im just overriding the equals method). but now inorder to maintain the equals contract i should also override the hashcode method. but im not sure how to put in a implementation for hashcode that suits the equals method. here is what i have so far:
data class AddressModel(
var id_address: Int = 0,
var id_country: Int = 0,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is AddressModel)
return false
else {
if (other.id_address == this.id_address)
return true
}
return false
}
}
compiler highly suggest i override hashCode method. but i dont understand what to implement. in the equals override i simply want to check if addressModel has same Id as another, if it does ,then i assume its equal.
this is what i have so far:
override fun hashCode(): Int {
return Objects.hash(id_address, id_country);
}
but i think this is better:
override fun hashCode(): Int {
return Objects.hash(id_address); //base hash off same as equals the id_address
}
this is recommended way i read but what does it mean ? if i added more class fields would i need to add more fields to the Objects.hash method also ? i would prefer the old skool way to do it as this call requires android api 19 and i support lower (api 16).
to be clear, i understand that If i don't override hashcode along with equals then every instance, e.g. "new AddressModel(707, 867)", will have a different hashcode. and then the HashMap for example will think these objects are distinct and not equal to replace them when calculating the hash for storage. but i just dont know what to put in the hashCode implementation. you can show me in either kotlin or java its ok.
update: would this be sufficient:
override fun hashCode(): Int { return id_address.hashCode() }