黑马程序员技术交流社区

标题: 遍历嵌套Map集合的问题 [打印本页]

作者: zhoubo    时间: 2016-7-21 20:11
标题: 遍历嵌套Map集合的问题
使用增强for循环遍历嵌套Map集合总是搞不清楚第二个for循环的数据类型和变量 有没有标准代码演示
作者: q123123    时间: 2016-7-21 21:54
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);
                        }
                }
               
        }

以前自己打的,键为自定义对象, 自己添加学生对象
作者: rockphoenix    时间: 2016-7-21 22:04
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,可能语言有些混乱,见谅...





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2