1. 程式人生 > >集合框架_ArrayList儲存自定義物件並遍歷增強for版

集合框架_ArrayList儲存自定義物件並遍歷增強for版

package cn.itcast_01;

import java.util.ArrayList;
import java.util.Iterator;

/*
 * ArrayList儲存自定義物件並遍歷。要求加入泛型,並用增強for遍歷。
 * A:迭代器
 * B:普通for
 * C:增強for
 * 
 * 
 * 增強for是用來替代迭代器的
 */
public class ArrayListDemo2 {
	public static void main(String[] args) {
		// 建立集合物件
		ArrayList<Student> array = new ArrayList<Student>();

		// 建立學生物件
		Student s1 = new Student("張三", 33);
		Student s2 = new Student("李四", 34);
		Student s3 = new Student("王五", 53);
		Student s4 = new Student("錢六", 22);
		Student s5 = new Student("特朗普", 50);

		// 把學生物件新增到集合物件中
		array.add(s1);
		array.add(s2);
		array.add(s3);
		array.add(s4);
		array.add(s5);

		// 遍歷集合
		// 迭代器
		Iterator<Student> it = array.iterator();
		while (it.hasNext()) {
			Student s = it.next();
			System.out.println(s.getName() + "---" + s.getAge());
		}
		System.out.println("------------------");
		// 普通for
		for (int x = 0; x < array.size(); x++) {
			Student s = array.get(x);
			System.out.println(s.getName() + "---" + s.getAge());
		}
		System.out.println("------------------");
		// 增強for
		if (array != null) {
			for (Student s : array) {
				System.out.println(s.getName() + "---" + s.getAge());
			}
		}
	}
}