2014-01-23 34 views
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()往往不夠。

+1

您是否爲鳥定義了.hashCode()和.equals()方法? – JustinKSU

+2

這些鍵似乎是字符串,而.hashCode()和.equals()對於這些值無關緊要。 –

+0

@JustinKSU不能!那些是什麼?我遵循[this](http://www.tutorialspoint.com/java/util/hashmap_get.htm)。 – Celeritas

回答

7

當您撥打substring時,請記住,結尾索引不包含在子字符串中。

子字符串開始在指定的beginIndex並延伸到字符索引endIndex - 1

在您的通話

input.substring(0, input.length()-1) 

你實際上採取的最後一個字符掉目前無論是input。所以,如果您有密鑰"finch",您無意中查找了密鑰"finc"

我根本沒有看到substring調用的原因;刪除:

Map<String, Birds> hint = new HashMap<>(); 

然後,調用get時,您不再需要:

Birds temp = (Birds) hint.get(input.trim()); 

此外,如果您提供的泛型類型參數,你HashMap,像這樣投給Birds是不必要的演員表:

Birds temp = hint.get(input.trim());