我的一门课中有以下方法。它只是一个 HashMap(名为 teamOfPlayer,带有 Player 对象的键和 Integer 对象的值)的公共包装器,仅此而已。
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(main.data.entities.Player@89f632df)
hash of argument is -1980353825
keySet() of hashmap is [main.data.entities.Player@89f632df]
containsKey() of hashmap is false
player extracted from keySet() is main.data.entities.Player@89f632df
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;
}