I have a class representing DB-Entries with a unique Id attribute.
Is is OK to implement the equals()
and hashcode()
methods only based on this attribute
@Override public int hashCode()
{ return id;
}
@Override public boolean equals(Object obj)
{
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Task other = (Task) obj;
if (id != other.id)
return false;
return true;
}
Java hashCode() An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
Case 1: Overriding both equals(Object) and hashCode() method Whenever it(hashcode) is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
"If two objects are equal using Object class equals method, then the hashcode method should give the same value for these two objects." So, if in our class we override equals() we should override hashcode() method also to follow this rule.
Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...
In general, yes. If all the ids are small consecutive integers, you could get better performance from big collections by using a function which distributed the bits more widely throughout the available 32 bits. But this should work find otherwise.
I don't see anything wrong with this code. However, there are some questions you might wish to ponder:
id
?If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With