Phoenix
Phoenix

Reputation: 8923

Why am I getting different hashcode values using hashcode builder for 2 equal objects?

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()

Upvotes: 5

Views: 1331

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1501023

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.

Upvotes: 12

Related Questions