4

A BigInteter is too big to be converted into an integer. But I have to store objects with an id (SHA 512) in a HashMap and need a hash function without many collisions.

I tried this. however, I am not sure if there is no clustering somewhere.

@Override
public boolean equals(Object obj) {
    if (this == obj) {
        return true;
    }
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    Advertisement other = (Advertisement) obj;
    return this.getId().equals(other.getId());
}

@Override
public int hashCode() {
    return new BigInteger(getId(), 16).hashCode();
}

would be a cast to an integer (bi.intValue()) more efficient?

1 Answer 1

6

Don't try to reinvent the wheel - simply use getId().hashCode():

@Override
public int hashCode() {
    return getId().hashCode();
}


String.hashCode() uses an efficient, high-quality hashing algorithm, so it's the best choice. And it makes your code simpler, which is always a good thing.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.