I'm having trouble using my own class as a key for a HashMap
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 && 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; } }
Here is a failed JUnit test
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());
dlundquist
source share