集合巢狀儲存和遍歷元素的示例
阿新 • • 發佈:2018-12-12
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 }