要求:创建一个集合,该集合中每个元素都是集合,实现该集合的遍历
package it.cast03;
import java.util.ArrayList;
import java.util.Iterator;
/**
* 嵌套集合
* @author Administrator
*
*/
public class Test {
public static void main(String[] args) {
//创建集合对象
ArrayList<Student> alist1 = new ArrayList<Student>();
ArrayList<Student> alist2 = new ArrayList<Student>();
ArrayList<Student> alist3 = new ArrayList<Student>();
//注意这里的泛型就是集合,而集合是和泛型基本一起出现,所以是ArrayList<Student>
ArrayList<ArrayList<Student>> alists = new ArrayList<ArrayList<Student>>();
//创建元素对象
Student s1 = new Student("a1",10);
Student s2 = new Student("a2",10);
Student s3 = new Student("a3",10);
Student s4 = new Student("b1",20);
Student s5 = new Student("b2",20);
Student s6 = new Student("c1",30);
Student s7 = new Student("c2",30);
Student s8 = new Student("c3",30);
Student s9 = new Student("c4",30);
Student s10 = new Student("c5",30);
//将元素对象添加到集合中
alist1.add(s1);
alist1.add(s2);
alist1.add(s3);
alist2.add(s4);
alist2.add(s5);
alist3.add(s6);
alist3.add(s7);
alist3.add(s8);
alist3.add(s9);
alist3.add(s10);
alists.add(alist1);
alists.add(alist2);
alists.add(alist3);
//对外层集合进行迭代
for(ArrayList<Student> list : alists){
//对内层的集合进行迭代
for(Student s : list){
System.out.println(s.getName()+"----"+s.getAge());
}
System.out.println("*********");
}
System.out.println("----------------------------");
//第二种方式迭代器
Iterator<ArrayList<Student>> it = alists.iterator();
//对外层集合进行迭代
while(it.hasNext()){
ArrayList<Student> alist = it.next();
Iterator<Student> itt = alist.iterator();
//对内层的集合进行迭代
while(itt.hasNext()){
Student s = itt.next();
System.out.println(s.getName()+"----"+s.getAge());
}
System.out.println("*********");
}
}
}
class Student{
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
运行结果
a1----10
a2----10
a3----10
*********
b1----20
b2----20
*********
c1----30
c2----30
c3----30
c4----30
c5----30
*********
----------------------------
a1----10
a2----10
a3----10
*********
b1----20
b2----20
*********
c1----30
c2----30
c3----30
c4----30
c5----30
*********
网友评论