title: User defined Key Class for HashMap
body: <p>I want to use HashMap to help count a pair element's number.
  Here I have a class Pair as follows:</p>
  
  <pre><code>class Pair{
  String s1;
  String s2;
  Pair(String ss1,String ss2) {
      s1 = ss1;
      s2 = ss2;
  }
  public int hashCode(){
      Integer a = Integer.valueOf(s1);
      Integer b = Integer.valueOf(s2);
      return 31 * a + b;
  }
  public boolean equals(Pair c) {
      if (c == null) return false; 
      if (this.s1.equals(c.s1) &amp;&amp; this.s2.equals(c.s2)) return true;
      return false;
  }
  }
  </code></pre>
  
  <p>I applied my Pair class to a HashMap</p>
  
  <pre><code>HashMap&lt;Pair,Integer&gt; map1 = new HashMap&lt;Pair,Integer&gt;();
  while (...) {
      Pair p = new Pair(word, lastword);
      if (map1.get(p) == null) {
          map1.put(p,0);
      }
      map1.put(p,map1.get(p)+1);
  }
  </code></pre>
  
  <p>Although I have defined hashCode and equals function in my Pair class. My code map1.get(p) == null would always be true as if the map never see a pair with two same string.
  Finally, the output is:</p>
  
  <pre><code>7 , 2 : 1
  7 , 2 : 1
  7 , 2 : 1
  7 , 2 : 1
  7 , 2 : 1
  7 , 2 : 1
  7 , 2 : 1
  </code></pre>
  
  <p>instead of </p>
  
  <pre><code>7 , 2 : 7
  </code></pre>
  
  <p>which means my map treats every Pair("7","2") as a different pair although they have the same hash code.</p>
  
  <p>Could anyone tell my where I do wrong in the design of Pair class ?</p>
  
  <p>Thanks.</p>