Search code examples
javahashcode

Hash Code Builder generate duplicate hash code


I want to get 2 hash code of 2 difference group number as below but they have the same result. I can not understand why this happen. Please help to resolve this issue.

new HashCodeBuilder(17, 37).append(8079).append(7540).append(15774).toHashCode();
new HashCodeBuilder(17, 37).append(8099).append(6801).append(15737).toHashCode();

enter image description here

I expect the result must have difference hash code.


Solution

  • It is just the way HashCodeBuilder builds the hash code. It just happens that you get the same result for these numbers

    new HashCodeBuilder(17, 37).append(8079).append(7540).append(15774).toHashCode()
    int iTotal = 17;
    int iConstant = 37;
    iTotal = iTotal * iConstant + 8079;
    iTotal = iTotal * iConstant + 7540;
    iTotal = iTotal * iConstant + 15774;
    

    iTotal = 12216006

    new HashCodeBuilder(17, 37).append(8099).append(6801).append(15737).toHashCode()
    iTotal = 17;
    iConstant = 37;
    iTotal = iTotal * iConstant + 8099;
    iTotal = iTotal * iConstant + 6801;
    iTotal = iTotal * iConstant + 15737;
    

    iTotal = 12216006

    You can get different values by using a different initial number for one of them, 19 instead of 17 for example. But there will be cases where 2 objects have the same hashcode. Hashcodes are not guaranteed to be unique.

    This is the HashCodeBuilder code:

    public HashCodeBuilder(int initialOddNumber, int multiplierOddNumber) {
        Validate.isTrue(initialOddNumber % 2 != 0, "HashCodeBuilder requires an odd initial value", new Object[0]);
        Validate.isTrue(multiplierOddNumber % 2 != 0, "HashCodeBuilder requires an odd multiplier", new Object[0]);
        this.iConstant = multiplierOddNumber;
        this.iTotal = initialOddNumber;
    }
    
    public HashCodeBuilder append(int value) {
        this.iTotal = this.iTotal * this.iConstant + value;
        return this;
    }