1

I was reading the code for the Arrays.hashCode provided below,

public static int hashCode(Object a[]) {
        if (a == null)
            return 0;

        int result = 1;

        for (Object element : a)
            result = 31 * result + (element == null ? 0 : element.hashCode());

        return result;
    }

I find it's not as clear as for why 31 is chosen for the hashing.

Secondly, the element.hashCode() send me to the Object class that defines it:

@HotSpotIntrinsicCandidate
public native int hashCode();

How the element.hashCode() is calculaed for the each iteration?

Thank you.

Tadija Malić
  • 445
  • 7
  • 26
Arefe
  • 11,321
  • 18
  • 114
  • 168
  • 1
    `I find it's not as clear as for why 31 is chosen for the hashing.` because its prime. – tkausl Mar 02 '19 at 08:21
  • @tkausl There many smaller primes as well, for example, why the `17` is not chosen? There might be some strong reasoning behind. – Arefe Mar 02 '19 at 08:22
  • It shows why using magic-numbers is not a good practice. – c0der Mar 02 '19 at 08:23
  • @AmitBera That link explain well. Shortly, Java choose 31 to optimize calculating costs. – 서강원 Mar 02 '19 at 08:28
  • "How the element.hashCode() is calculaed" - each class can implement (override) the `hashCode` method; e.g. `Integer` just returns its value – user85421 Mar 02 '19 at 08:31
  • @CarlosHeuberger I think the question is what does `native` mean and also what a hotspot intrinsic candidate is? i.e. no one is _forced_ to override `hashCode()`. – Boris the Spider Mar 02 '19 at 08:36

1 Answers1

3

From the book Effective Java:

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55