集合嵌套存储和遍历元素的示例

 1 /**
 2  * @Auther: lzy
 3  * @Date: 2018/12/12 16:07
 4  * @Description: 集合嵌套存储和遍历元素的示例
 5  */
 6 public class ListTest {
 7     public static void main(String[] args) {
 8         //创建大集合
 9         ArrayList<ArrayList<Student>> bigArrayList = new ArrayList<ArrayList<Student>>();
10         //创建第一个小集合
11         ArrayList<Student> firstArrayList = new ArrayList<Student>();
12         //创建学生
13         Student s1 = new Student("fff",22);
14         Student s2 = new Student("hhh",21);
15         Student s3 = new Student("nnn",20);
16         //把学生存储到第一个小集合中
17         firstArrayList.add(s1);
18         firstArrayList.add(s2);
19         firstArrayList.add(s3);
20         //把第一个小集合存储到大集合中
21         bigArrayList.add(firstArrayList);
22         //创建第二个小集合
23         ArrayList<Student> secondArrayList = new ArrayList<Student>();
24         Student s21 = new Student("sss",22);
25         Student s22 = new Student("xxx",21);
26         Student s23 = new Student("zzz",20);
27         secondArrayList.add(s21);
28         secondArrayList.add(s22);
29         secondArrayList.add(s23);
30         bigArrayList.add(secondArrayList);
31         //遍历大集合
32         for (ArrayList<Student> arrayList:bigArrayList){
33             //遍历小集合
34             for (Student s:arrayList){
35                 System.out.println(s.getName()+","+s.getAge());
36             }
37 
38         }
39 
40 
41     }
42 }

猜你喜欢

转载自www.cnblogs.com/lzy-417/p/10109201.html