title: Java hashcode() strings collision
body: <p>I do not know much about hashcodes. I found this code which prints the collisions. </p>
  
  <p>Can you please tell me what are collisions and how to reduce it?
  Why should we use hashcodes?</p>
  
  <pre><code>public static int getHash(String str, int limit)
  {
      int hashCode = Math.abs(str.hashCode()%(limit));
      return hashCode;
  }
  
  /**
   * @param args
   */
  public static void main(String[] args)
  {
      int hashLimit = 10000;
      int stringsLimit = 10000;
      String[] arr = new String[hashLimit];
      List&lt;String&gt; test = new ArrayList&lt;String&gt;();
      Random r = new Random(2);
      for ( int i = 0 ; i &lt; stringsLimit ; i++ )
      {
          StringBuffer buf = new StringBuffer("");
          for ( int j = 0 ; j &lt; 10 ; j++ )
          {
              char c = (char)(35+60*r.nextDouble());
              buf.append(c);
          }
          test.add(buf.toString());
          //System.out.println(buf.toString());
      }
      int collisions = 0;
      for ( String curStr : test )
      {
          int hashCode = getHash(curStr,hashLimit);
          if ( arr[hashCode] != null &amp;&amp; !arr[hashCode].equals(curStr) )
          {
              System.out.println("collision of ["+arr[hashCode]+"] ("+arr[hashCode].hashCode()+" = "+hashCode+") with ["+curStr+"] ("+curStr.hashCode()+" = "+hashCode+")");
              collisions++;
          }
          else
          {
              arr[hashCode] = curStr;
          }
      }
      System.out.println("Collisions: "+collisions);
  }
  </code></pre>