1
我打印出要搜索的密鑰和地圖中的密鑰,它們在那裏但分配失敗。我通過用一個對象填充地圖進行測試並遍歷並打印出鍵。我正在引用的關鍵是在那裏,所以我不能看到如何臨時爲空?爲什麼在hashmap中找不到密鑰?
Birds temp = (Birds)hint.get(input.substring(0, input.length()-1).trim());//the last char is being dropped off on purpose
if(temp == null)
{
System.out.println("failed to map key");
Iterator entries = hint.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry thisEntry = (Map.Entry) entries.next();
System.out.println("Key1: "+
thisEntry.getKey()); //this an next line printout the same
System.out.println("key2: "+
input.substring(0, input.length()-1).trim());
}
}
我添加以下行鳥類,但還是原來的白色空間被擰的事情了同樣的問題
@Override public int hashCode()
{
return name.hashCode();
}
@Override
public boolean equals(Object obj) {
Bird b = (Bird)obj;
String str = b.name;
if(str.compareTo(this.name) == 0)
return true;
else
return false;
}
,我並沒有叫trim()
往往不夠。
您是否爲鳥定義了.hashCode()和.equals()方法? – JustinKSU
這些鍵似乎是字符串,而.hashCode()和.equals()對於這些值無關緊要。 –
@JustinKSU不能!那些是什麼?我遵循[this](http://www.tutorialspoint.com/java/util/hashmap_get.htm)。 – Celeritas