Need an explanation of the hashcode example in the Effective Java Tutorial

Here is a sample code from paragraph 9:

public final class PhoneNumber {
  private final short areaCode;
  private final short prefix;
  private final short lineNumber;

  @Override
  public int hashCode() {
    int result = 17;
    result = 31 * result + areaCode;
    result = 31 * result + prefix;
    result = 31 * result + lineNumber;
    return result;
  }
}

PG 48 states: “The value 31 was chosen because it is odd prime . If it were even and the overflow overflowed, the information would be lost, since muiltiplication by 2 is equivalent to a shift.”

I understand that the concept of multiplying by 2 is equivalent to a bit offset. I also know that we will still get overflow (hence, loss of information) when we multiply a large number by a large odd prime number. What I am not getting is that the loss of information resulting from multiplication by large odd primes is preferable to the loss of information resulting from multiplication by large even numbers.

+5
2

. , result. , , .

+6

, - 2.

- #, , 3 5, , , , .

; , - . - , HashSet, HashMap .., , -, .

+1

All Articles