title: Why are custom objects not equivalent keys for a HashMap?
body: <p>I'm having trouble using my own class as a key for a HashMap</p>
  
  <pre><code> public class ActorId {
       private final int playerId;
       private final int id;
  
       ActorId(int playerId, int id) {
           this.playerId = playerId;
           this.id = id;
       }
  
       public boolean equals(ActorId other) {
           return this.id == other.id &amp;&amp; this.playerId == other.playerId;
       }
  
       public int hashCode() {
           int hash = 1;
           hash = hash * 31 + playerId;
           hash = hash * 31 + id;
           return hash;
       }
  
       public String toString() {
           return "#" + playerId + "." + id;
       }
  
       public int getPlayerId() {
           return playerId;
       }
   }
  </code></pre>
  
  <p>Here is a failing JUnit test</p>
  
  <pre><code> import static org.junit.Assert.*;
   import java.util.Map;
   import org.junit.Test;
  
   public class ActorIdTest {
       @Test
       public final void testAsMapKey() {
           ActorId a = new ActorId(123, 345);
           ActorId b = new ActorId(123, 345);
  
           assertTrue(a.equals(b));
           assertEquals(a.hashCode(), b.hashCode());
  
           // Works with strings as keys
           Map&lt;String, String&gt; map1 = new java.util.HashMap&lt;String, String&gt;();
  
           map1.put(a.toString(), "test");
           assertEquals("test", map1.get(a.toString()));
           assertEquals("test", map1.get(b.toString()));
           assertEquals(1, map1.size()); 
  
           // But not with ActorIds
           Map&lt;ActorId, String&gt; map2 = new java.util.HashMap&lt;ActorId, String&gt;();
  
           map2.put(a, "test");
           assertEquals("test", map2.get(a));
           assertEquals("test", map2.get(b)); // FAILS here
           assertEquals(1, map2.size()); 
  
           map2.put(b, "test2");
           assertEquals(1, map2.size());
           assertEquals("test2", map2.get(a));
           assertEquals("test2", map2.get(b));
       }
   }
  </code></pre>