首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对HashMap of HashMap的迭代

对HashMap of HashMap的迭代
EN

Stack Overflow用户
提问于 2014-07-13 02:21:02
回答 2查看 94关注 0票数 0

为什么这样做不对?

代码语言:javascript
复制
for (Entry<String, HashMap> temp : wordCountforFile.entrySet()) {
        System.out.println(temp.getKey());
        for(Entry<String, Integer> temp1: temp.getValue()){
            //Wrong?
        }
    }

其中: HashMap wordCountforFile =新HashMap();

代码语言:javascript
复制
HashMap<String, Integer> wordCount = new HashMap<String, Integer>();

代码语言:javascript
复制
wordCountforFile.put("Any String", wordCount);
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-13 02:24:28

这是错误的,因为您没有为HashMap temp指定泛型。此外,如果您期望有一个entrySet(),则应该在最内部循环中遍历Map.Entry。你应该使用:

代码语言:javascript
复制
for (Entry<String, HashMap<String, Integer>> temp : wordCountforFile.entrySet()) {
    System.out.println(temp.getKey());
    for(Entry<String, Integer> temp1 : temp.entrySet()){
        // ...
    }
}

顺便提一句,我通常会发现,如果您有一个Map的Map,这意味着其中一个映射在逻辑上表示某种实体,如果要将它移动到它自己的类中,这些实体就可以简化。这只是个想法。

票数 3
EN

Stack Overflow用户

发布于 2014-07-13 07:29:40

代码语言:javascript
复制
    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不是用泛型定义的。如果没有泛型,就应该进行显式浇铸。

代码语言:javascript
复制
   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()

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24718995

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档