A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© zhoubo 中级黑马   /  2016-7-21 20:11  /  638 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

使用增强for循环遍历嵌套Map集合总是搞不清楚第二个for循环的数据类型和变量 有没有标准代码演示

2 个回复

倒序浏览
public static void main(String[] args) {

                HashMap<Student, String> hm1 = new HashMap<>();
                hm1.put(new Student("张三",23), "上海");
                hm1.put(new Student("李四",24), "北京");
               
                HashMap<Student, String> hm2 = new HashMap<>();
                hm2.put(new Student("王五",21), "郑州");
                hm2.put(new Student("赵六",22), "广州");
               
                HashMap<HashMap<Student, String>,String> hm3 = new HashMap<>();
                hm3.put(hm1, "第88期");
                hm3.put(hm2, "第89期");
                for (HashMap<Student, String> s1 : hm3.keySet()) {
                        for (Student s2 : s1.keySet()) {
                                System.out.println(hm3.get(s1) + s1.get(s2) + s2);
                        }
                }
               
        }

以前自己打的,键为自定义对象, 自己添加学生对象
回复 使用道具 举报
HashMap<Student, String> h1= new HashMap();//创建双列集合对象h1
HashMap<Student, String> h2= new HashMap();//创建双列集合对象h2
h1.put(new Student("德里克罗斯", 28), "控球后卫");//h1中添加元素
h2.put(new Student("凯文加内特",40), "大前锋");//h2中添加元素
HashMap<HashMap<Student>, String> h3 = new HashMap();//创建双列集合对象h
hList.put(h1,"尼克斯");//h中添加集合h1hList.put(h2,"森林狼");//h中添加集合h2

for(HashMap<Student> h4 : h3.keySet()){//增强for循环遍历集合h       String str = h3.get(h);//这里获得h的值,尼克斯,开拓者
       for(Student stu : h4.keySet()){//增强for循环遍历h1,h2
              String s = h4.get(stu);//创建String型变量存储h1,h2的值,控球后卫,大前锋
              syso(stu + s);姓名是德里克罗斯,年龄28,控球后卫;姓名是凯文加内特,年龄40,大前锋
       }
}


第一层循环的键是第二层循环要遍历的对象,如例子中,第二层要遍历的对象(第一层的键)是h1,h2,而我们用h4表示;第二层的变量则是h1,h2的键,
我们用stu表示,stu因为是Student类对象,我们已经改写过toString()方法,就不用管它了,直接输出就行,每层for循环我个人理解就是第一层循环<>里的是第二层冒号后要写的遍历对象,第二层循环<>里的是该层遍历对象的泛型,比如例子中的Student,可能语言有些混乱,见谅...
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马