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

集合框架_ArrayList儲存自定義物件並遍歷泛型版

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());
		}
	}
}