What am I doing wrong here ?
@Override
public int hashCode()
{
HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();
hashCodeBuilder.append(this.getId()).append(this.getDocFamilyUuid())
.append(this.getCorrelationId());
return hashCodeBuilder.hashCode();
}
This is how I'm creating the object in groovy. The fields are being set to static constants
DocInfo docInfo = new DocInfo(id:DOC_ID, correlationId: CORRELATION_ID, docFamilyUuid: DOC_FAMILY_UUID)
And I'm trying to assert
assert docInfo.hashCode() ==
new DocInfo([id:DOC_ID,
correlationId: CORRELATION_ID,
docFamilyUuid:DOC_FAMILY_UUID]).hashCode()
1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.
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.
When two objects are equal, you must override hashcode so that the hashcodes are equal too. Otherwise you will have problems when you use the object in a collection. In your given example, they have written If you override equals(), you must override hashCode() as well.
The only contractual obligation for hashCode is for it to be consistent. The fields used in creating the hashCode value must be the same or a subset of the fields used in the equals method. This means returning 0 for all values is valid, although not efficient.
I suspect the problem is that you're calling hashCode()
instead of toHashCode()
, assuming you're using the commons-lang HashCodeBuilder. In other words, you're getting the hash code of the builder itself, rather than the hash code it's building :)
Now the odd thing is that they're documented to return the same thing in the version of the JavaDoc that I've linked to. So I wonder whether you've got an old version - or possibly you're using an entirely different HashCodeBuilder
entirely...
EDIT: Yup, HashCodeBuilder.hashCode()
is overridden in version 2.5+ to return toHashCode()
, but the OP is using version 2.3, which doesn't work that way.
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