Why am I getting different hash values ​​using the 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 create an object in groovy. Fields are set to static constants.

DocInfo docInfo =  new DocInfo(id:DOC_ID, correlationId: CORRELATION_ID, docFamilyUuid: DOC_FAMILY_UUID)

And I'm trying to argue

assert docInfo.hashCode() ==
           new DocInfo([id:DOC_ID,
                   correlationId: CORRELATION_ID,
                   docFamilyUuid:DOC_FAMILY_UUID]).hashCode()
+5
source share
1 answer

I suspect the problem is what you are calling hashCode()instead toHashCode()if you use commons-lang HashCodeBuilder . In other words, you get the hash code of the builder itself, and not the hash code that it creates :)

, , JavaDoc, . , - , , HashCodeBuilder ...

EDIT: Yup, HashCodeBuilder.hashCode() 2.5+, toHashCode(), OP 2.3, .

+12

All Articles