集合框架(集合嵌套存储和遍历元素)-
集合嵌套和遍历元素
package Day16;
import java.util.ArrayList;
public class LX15 {
public static void main(String[] args) {
//创建集合1-----规定其类型为学生类型
ArrayList<Student> A = new ArrayList<Student>();
//向集合1内添加元素
//创建学生对象并添加元素
Student AA = new Student("刘备",30);
Student BB = new Student("关羽",29);
Student CC = new Student("张飞",28);
//将学生类的元素添加到集合1中
A.add(AA);
A.add(BB);
A.add(CC);
//创建集合2--规定其类型为学生类型
ArrayList<Student> B = new ArrayList<Student>();
//向集合2中添加元素
//创建学生对象并添加元素
Student AAA = new Student("唐僧",30);
Student BBB = new Student("孙悟空",29);
Student CCC = new Student("猪八戒",28);
Student DDD = new Student("沙僧",27);
//将学生对象的信息添加到集合2中
B.add(AAA);
B.add(BBB);
B.add(CCC);
B.add(DDD);
//创建集合3-规定其类型为学生类型
ArrayList<Student> C = new ArrayList<Student>();
//向集合3中添加学生对象元素
//创建学生对象
Student AAAA = new Student("宋江",43);
Student BBBB = new Student("武松",42);
Student CCCC = new Student("鲁智深",41);
Student DDDD = new Student("吴用",40);
//向集合3中添加学生类对象
C.add(AAAA);
C.add(BBBB);
C.add(CCCC);
C.add(DDDD);
//创建一个D集合---集合中包含着三个集合
//前三个集合的类型为ArrayList<Student>类型
ArrayList<ArrayList<Student>> D = new ArrayList<ArrayList<Student>>();
//向集合D中添加集合A,B,C元素
D.add(A);
D.add(B);
D.add(C);
//对所有集合元素进行遍历
//首先对大集合进行遍历---增强for
//for(数据类型 变量 :数组或者集合名)
for(ArrayList<Student> x: D){
//此时遍历获取小集合
//对小集合进行增强for的遍历
//确定遍历的数据类型
for(Student y : x){
System.out.println(y.getName()+"---"+y.getAge());
}
}
}
}


