天天看点

集合框架_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());
    }
  }
}