title: What's behind the hashCode() method for String in Java?
body: <p>I've been investigating the <code>hashCode()</code> methods in java and found the one for String class strange. The source code is as follows:</p>
  
  <pre><code>public int hashCode() {
      int h = hash;
      if (h == 0 &amp;&amp; value.length &gt; 0) {
          char val[] = value;
  
          for (int i = 0; i &lt; value.length; i++) {
              h = 31 * h + val[i];
          }
          hash = h;
      }
      return h;
  }
  </code></pre>
  
  <p>The code itself is quite straight forward. But I wonder what's the reason for calculating hash code this way?<br> Why choose 31?<br> Why start from 0 instead of value.length - 1?<br> Any guarantee that this would make hashcodes less possible to collide with each other?</p>