黑马程序员技术交流社区
标题:
分享一个嵌套集合程序,帮忙看看注释是否有误
[打印本页]
作者:
ZZGFF
时间:
2015-3-1 22:11
标题:
分享一个嵌套集合程序,帮忙看看注释是否有误
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
/*
* ArrayList嵌套HashMap:
*
* 将0118班存到一个Map<String,ArrayList<Student>>
* 将0120班存到一个Map<String,ArrayList<Student>>
*/
public class Demo1 {
public static void main(String[] args) {
// Student对象已经封装好。一个name一个age这里就不拿上来了。直接使用
// 第一个班,以及学生:
// 创建ArrayList<Student>集合
ArrayList<Student> stuArrList1 = new ArrayList<>();
// 创建学生对象并添加到stuArrList1集合中
stuArrList1.add(new Student("小明", 15));
stuArrList1.add(new Student("小红", 16));
// 创建HashMap集合
HashMap<String, ArrayList<Student>> hMap1 = new HashMap<>();
// 将创建好的stuArrLsit1添加到hMap1集合中
hMap1.put("0118班", stuArrList1);
// 第二个班,以及学生:同上
ArrayList<Student> stuArrList2 = new ArrayList<>();
stuArrList2.add(new Student("大明", 20));
stuArrList2.add(new Student("大红", 18));
HashMap<String, ArrayList<Student>> hMap2 = new HashMap<>();
hMap2.put("0120班", stuArrList2);
// 将创建好的两个班级存入一个ArrayList集合中
ArrayList<HashMap<String, ArrayList<Student>>> lastArrList = new ArrayList<>();
lastArrList.add(hMap1);
lastArrList.add(hMap2);
// 使用增强for循环遍历
// 遍历lastArrList
for (HashMap<String, ArrayList<Student>> map : lastArrList) {
// 获取map中的键,但此时他还在HashMap中需要遍历拿出。
Set<String> keySet = map.keySet();
// 遍历keySet
for (String key : keySet) {
// 到了这里就获取到了HashMap<String,ArrayList<Student>>中的键值:0118班,0120班
// 打印键值
System.out.println(key);
// 获取map中的值的地址
ArrayList<Student> arrList = map.get(key);
// 遍历arrList
for (Student stu : arrList) {
// 打印学生信息
System.out.println("\t" + stu.getName() + ","
+ stu.getAge());
}
}
}
/*
* 结果: 0118班 小明,15 小红,16 0120班 大明,20 大红,18
*/
}
}
复制代码
作者:
ZZGFF
时间:
2015-3-1 22:12
结果是:
0118班
小明,15
小红,16
0120班
大明,20
大红,18
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2