我在其中一个类中有以下方法。它只是一个围绕HashMap(名为teamOfPlayer,包含Player对象的键和Integer对象的值)的公共包装,仅此而已。HashMap.get()使用继承的hashCode()方法正常工作,无法用用户定义的hashCode()方法识别密钥
public int getTeamOfPlayer(Player p)
{
return teamOfPlayer.get(p);
}
只要我的Player对象从Object继承默认的hashCode()方法,这工作得很好。但是,为了将我的Player对象保存到文件中,我实现了自己的hashCode()。突然间,该方法开始抛出一个NullPointerException。
我扩展了下面的方法来打印出一些调试信息,但这让我更加困惑。
public int getTeamOfPlayer(Player p)
{
Object[] o = teamOfPlayer.keySet().toArray();
Player p2 = (Player) o[0];
System.out.println("getTeamOfPlayer(" + p + ")"
+ "\n\thash of argument is " + p.hashCode()
+ "\n\tkeySet() of hashmap is " + teamOfPlayer.keySet()
+ "\n\tcontainsKey() of hashmap is " + teamOfPlayer.containsKey(p)
+ "\n\tplayer extracted from keySet() is " + p2
+ "\n\tplayer extracted from keySet() has hash of" + p2.hashCode()
+ "\n\targument.equals(key) returns " + p.equals(p2)
+ "\n\tkey.equals(argument) returns " + p2.equals(p));
int i = teamOfPlayer.get(p);
return i;
}
上述方法的输出是在这里:
getTeamOfPlayer([email protected])
hash of argument is -1980353825
keySet() of hashmap is [[email protected]]
containsKey() of hashmap is false
player extracted from keySet() is [email protected]
player extracted from keySet() has hash of-1980353825
argument.equals(key) returns true
key.equals(argument) returns true
的抛出异常的 “INT I = teamOfPlayer.get(P);”这意味着地图返回null(因为它不认为它包含关键字)。我知道这就是抛出异常的原因。不过,我认为我已经证明了地图中存在的关键因素。这是怎么回事?
-
更新: 这里是equals()和hashCode()方法。
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
Player player;
if (obj != null && obj instanceof Player)
player = (Player) obj;
else
return false;
if (status != player.status || !name.equals(player.name) || race != player.race || weeksOut != player.weeksOut || injuryType != player.injuryType
|| XP != player.XP)
return false;
for (int i = 0; i < 8; i++)
{
if (attributes[i] != player.attributes[i])
return false;
if (injuries[i] != player.injuries[i])
return false;
}
for (int i = 0; i < 28; i++)
{
if (hasSkill[i] != player.hasSkill[i])
return false;
}
for (int i = 0; i < 4; i++)
{
if (equipment[i] != player.equipment[i])
return false;
}
return true;
}
@Override
public int hashCode()
{
int hash = 11;
hash = 31 * hash + status;
hash = 31 * hash + name.hashCode();
hash = 31 * hash + race;
hash = 31 * hash + weeksOut;
hash = 31 * hash + injuryType;
hash = 31 * hash + XP;
for (int i = 0; i < 8; i++)
{
hash = 31 * hash + attributes[i];
hash = 31 * hash + injuries[i];
}
for (int i = 0; i < 28; i++)
hash = hash + (hasSkill[i] ? 1 : 0);
for (int i = 0; i < 4; i++)
hash = 31 * hash + equipment[i];
return hash;
}
你是否重写'equals'以与hashCode一致? – rgettman
请发布您的hashCode()和equals()方法的代码 – NickJ
@rgettman您可以从调试输出中看到,不仅两个对象具有相同的哈希码,而且它们也相互平等。 –