1. 程式人生 > >ArrayList儲存自定義物件並遍歷,要求加入泛型,並用增強for遍歷

ArrayList儲存自定義物件並遍歷,要求加入泛型,並用增強for遍歷

import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo1 {


public static void main(String[] args) {
//建立集合物件
ArrayList<Student> array = new ArrayList<Student>();

//建立學生物件
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("吳居蘭",18);
Student s3 = new Student("王守義",46);

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

//建立迭代器
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
for(Student s : array) {
System.out.println(s.getName()+"----"+s.getAge());
}
}


}