Maxime
Maxime

Reputation: 1816

Could you explain the so called Java standard way to compute hashcode?

I recently have to override the equals and hashCode methods in Java. I hence looked for a fast and efficient way to compute hash codes.

Java developers seem to aggree on the following method :

    int hash = 23;
    hash = hash * 37 + paramOne;
    hash = hash * 37 + paramTwo;
    // And so on...

It might be simple arithmetic but I don't really get it. What are the garantees ? What are the corner cases ? Is there a better (rather simple) way to do it ?

Thank you !

Upvotes: 1

Views: 171

Answers (3)

duffymo
duffymo

Reputation: 308848

Joshua Bloch tells you how to override equals and hashCode properly in chapter 3 of his "Effective Java". Google for it and read it.

He's the guy who wrote the collections API and is now the chief Java architect for Google. That's authoritative enough for me.

Upvotes: 1

Kazekage Gaara
Kazekage Gaara

Reputation: 15052

In words of Joshua Bloch (explaining the default implementation of hashCode() method in String class , that is : s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]):

The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically.

For further reading , refer this and this.

Upvotes: 2

Urs Reupke
Urs Reupke

Reputation: 6921

It's about prime factors. Have a look at this answer.

If you're just looking for a fast way and pragmatic way to do it and you have no major concerns about performance, have a look at the Apache Commons Lang HashCodeBuilder or a similar library function. There is an equivalent builder for equals.

Upvotes: 2

Related Questions