我用我自己的類作爲一個HashMap爲什麼自定義對象不是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;
}
}
這裏的關鍵有麻煩的是一個失敗的JUnit測試
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<String, String> map1 = new java.util.HashMap<String, String>();
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<ActorId, String> map2 = new java.util.HashMap<ActorId, String>();
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));
}
}
你說它在'... map2.get(b)'上失敗 - 你在Map中沒有這樣的鍵。你只向地圖添加了一個對象,即'a'實例。 – 2011-06-05 09:12:20
@Björn是的,兩個ActorId對象是相等的並且具有相同的哈希碼,所以它們應該從地圖返回相同的值。 – dlundquist 2011-06-05 09:16:59
呃,對不起!剛剛從牀上爬起來,應該已經讀完了整個代碼塊。 – 2011-06-05 09:18:28