为什么这样做不对?
for (Entry<String, HashMap> temp : wordCountforFile.entrySet()) {
System.out.println(temp.getKey());
for(Entry<String, Integer> temp1: temp.getValue()){
//Wrong?
}
}其中: HashMap wordCountforFile =新HashMap();
HashMap<String, Integer> wordCount = new HashMap<String, Integer>();和
wordCountforFile.put("Any String", wordCount);发布于 2014-07-13 02:24:28
这是错误的,因为您没有为HashMap temp指定泛型。此外,如果您期望有一个entrySet(),则应该在最内部循环中遍历Map.Entry。你应该使用:
for (Entry<String, HashMap<String, Integer>> temp : wordCountforFile.entrySet()) {
System.out.println(temp.getKey());
for(Entry<String, Integer> temp1 : temp.entrySet()){
// ...
}
}顺便提一句,我通常会发现,如果您有一个Map的Map,这意味着其中一个映射在逻辑上表示某种实体,如果要将它移动到它自己的类中,这些实体就可以简化。这只是个想法。
发布于 2014-07-13 07:29:40
HashMap<String, HashMap<String, Integer>> wordCountforFile = new HashMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> wordCount = new HashMap<String, Integer>();
wordCountforFile.put("Any String", wordCount);
for (Map.Entry<String, HashMap<String, Integer>> temp : wordCountforFile.entrySet()) {
System.out.println(temp.getKey());
for(Map.Entry<String, Integer> temp1: temp.getValue().entrySet()){
}
}
}wordCountForFile不是用泛型定义的。如果没有泛型,就应该进行显式浇铸。
for(Map.Entry<String, HashMap<String, Integer>> temp : ((Set<Map.Entry<String, HashMap<String, Integer>>>) wordCountforFile.entrySet()))但是这并不总是安全的,因为如果条目不是String & HashMap类型,就会导致HashMap。如果映射中的键和值的类型已知以避免ClassCastException,那么最好使用泛型。
temp.getValue()返回字符串映射&要迭代此映射中的每个条目的Integer.If使用temp.getValue().entrySet()
https://stackoverflow.com/questions/24718995
复制相似问题