package cn.itcast_02;
import java.util.ArrayList;
import java.util.Iterator;
/*
* 需求:存储自定义对象,并遍历。
*
* 分析:
* A:创建学生类
* B:创建集合对象
* C:创建学生对象
* D:把学生对象添加到集合对象中
* E:遍历
*/
public class ArrayListDemo2 {
public static void main(String[] args) {
// 创建集合对象
// JDK7的新特性:泛型推断。
// ArrayList<Student> array = new ArrayList<>);
// 不建议这样使用
ArrayList<Student> array = new ArrayList<Student>();
// 创建学生对象
Student s1 = new Student("张三", 22);
Student s2 = new Student("李四", 26);
Student s3 = new Student("王五", 49);
Student s4 = new Student("赵六", 35);
Student s5 = new Student("王麻子", 25);
// 把学生对象添加到集合中
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
array.add(s5);
// 遍历
Iterator<Student> it = array.iterator();
while (it.hasNext()) {
Student stu = it.next();
System.out.println(stu.getName() + "---" + stu.getAge());
}
System.out.println("------------------");
// for循环
for (int x = 0; x < array.size(); x++) {
Student stu = array.get(x);
System.out.println(stu.getName() + "---" + stu.getAge());
}
}
}