Multiple choice

Which of the following is a code snippet for calculating the hashcode value of a string employed by Java compiler?

  1. public int hashCode(String s) { int h = 0; char val[] = s.toCharArray(); for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } } return h; }

  2. public int hashCode(String s) { int h = 0; char val[] = s.toCharArray(); for (int i = 0; i < value.length; i++) { h = 27 * h + val[i]; } } return h; }

  3. public int hashCode(String s) { int h = 0; char val[] = s.toCharArray(); for (int i = 0; i < value.length; i++) { h = 131 * h + val[i]; } } return h; }

  4. public int hashCode(String s) { int h = 0; char val[] = s.toCharArray(); for (int i = 0; i < value.length; i++) { h = 231 * h + val[i]; } } return h; }

  5. public int hashCode(String s) { int h = 0; char val[] = s.toCharArray(); for (int i = 0; i < value.length; i++) { h = 531 * h + val[i]; } } return h; }

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

31 is used because 31 * i == (i << 5) - i. This can be performed very quickly.