标签:集合的嵌套遍历
1.需求
我们班有学生,每一个学生是一个对象,那么我们可以用一个集合表示我们班级的学生ArrayList<Student>,但是呢?一个年级不可能只有一个班级,其他班级也是ArrayList<Student>。但是我现在如何用集合存储一个年级的学生呢。就像这样存储ArrayList<ArrayList<Student>>
2.图解
3.代码实现
package cn; import java.util.ArrayList; /** * 集合的嵌套遍历 * */ public class ArrayListDemo { public static void main(String[] args) { //创建年级集合 ArrayList<ArrayList<Student>> grand = new ArrayList<ArrayList<Student>> (); //创建班级1集合 ArrayList<Student> class01 = new ArrayList<Student>(); Student s011 = new Student("唐僧",30); Student s012 = new Student("孙悟空",29); Student s013 = new Student("猪八戒",28); Student s014 = new Student("沙僧",27); Student s015 = new Student("白龙马",26); class01.add(s011); class01.add(s012); class01.add(s013); class01.add(s014); class01.add(s015); //将班级1放入到年级 grand.add(class01); //创建班级2集合 ArrayList<Student> class02 = new ArrayList<Student>(); Student s021 = new Student("诸葛亮",30); Student s022 = new Student("司马懿",28); Student s023 = new Student("周瑜",26); class01.add(s021); class01.add(s022); class01.add(s023); //将班级2放入到年级 grand.add(class02); //创建班级3集合 ArrayList<Student> class03 = new ArrayList<Student>(); Student s031 = new Student("宋江",40); Student s032 = new Student("吴用",35); Student s033 = new Student("高俅",30); Student s034 = new Student("李师师",22); class01.add(s031); class01.add(s032); class01.add(s033); class01.add(s034); //将班级2放入到年级 grand.add(class03); //遍历集合 for(ArrayList<Student> grands : grand){ for(Student student : grands ){ System.out.println(student); } } } }
Student [name=唐僧, age=30]
Student [name=孙悟空, age=29]
Student [name=猪八戒, age=28]
Student [name=沙僧, age=27]
Student [name=白龙马, age=26]
Student [name=诸葛亮, age=30]
Student [name=司马懿, age=28]
Student [name=周瑜, age=26]
Student [name=宋江, age=40]
Student [name=吴用, age=35]
Student [name=高俅, age=30]
Student [name=李师师, age=22]
本文出自 “11831428” 博客,请务必保留此出处http://11841428.blog.51cto.com/11831428/1862389
标签:集合的嵌套遍历
原文地址:http://11841428.blog.51cto.com/11831428/1862389