感謝您閱讀我的文章。目前我正在做一個學校項目,不幸的是卡住了。我有一個我希望能夠遍歷並放入數組/列表結構的類型的散列圖。而不是使用Map.Entry,我有一個輔助類來使代碼不那麼棘手(即時通訊仍然被欺騙)。如何迭代哈希映射並放入數組/列表結構?
助手類:
class WordCount {
String word;
Integer count;
WordCount(String word, Integer count) {
this.word = word;
this.count = count;
}
}
,我已經試過這樣:
WordCount[] wc = new WordCount[hm.size()];
Iterator it = hm.entrySet().iterator();
int i = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
wc[i].word = (String) pair.getKey();
wc[i].count = (Integer) pair.getValue();
i++;
}
我得到的錯誤與然而該代碼。我有一種感覺,有一種更簡單的方法去這個...
爲什麼使用原始類型?泛型將消除大量這些強制類型,並使代碼更容易出錯。 – user2357112
你的hashmap是否有字符串字作爲鍵和int計數值?還是你有一個類對象而不是HashMap? –
如果您有任何例外或錯誤,請不要忘記將它們添加到問題中。 – Ian2thedv