天天看點

集合架構_List存儲學生對象并周遊

package cn.itcast_02;

public class Student {
  private String name;
  private int age;

  public Student() {
    super();
    // TODO Auto-generated constructor stub
  }

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

}      
package cn.itcast_02;

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

/*
 * 存儲自定義對象并周遊
 */
public class ListDemo {
  public static void main(String[] args) {
    // 建立集合對象
    List list = new ArrayList();
    
    //建立學生對易用
    Student s1 = new Student("張三",13);
    Student s2 = new Student("李四",14);
    Student s3 = new Student("王五",15);
    Student s4 = new Student("趙六",16);
    
    //把學生對象添加到集合對象中
    list.add(s1);
    list.add(s2);
    list.add(s3);
    list.add(s4);
    
    //周遊集合
    Iterator it = list.iterator();
    while(it.hasNext()){
      Student s = (Student) it.next();
      System.out.println(s.getName()+"---"+s.getAge());
    }
  }
}