//集合框架(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("曹操", 40); // 後知後覺
Student s2 = new Student("蔣幹", 30); // 不知不覺
Student s3 = new Student("諸葛亮", 26);// 先知先覺
// 添加元素
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 (int x = 0; x < array.size(); x++) {
Student s = array.get(x);
System.out.println(s.getName() + "---" + s.getAge());
}
}
}
學生類
package cn.itcast_02;
/**
* 這是學生描述類
*
* @author 風清揚
* @version V1.0
*/
public 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;
}
}