集合

写一个案例

用集合存储5个学生对象,并遍历这5个学生对象

package cn.itcast_02;

import java.util.ArrayList;
import java.util.Collection;

public class StudentDemo {

    /**用集合存储5个学生对象,并把学生对象遍历 
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Collection c = new ArrayList();
        Student s = new Student("明明", 20);
        Student s2 = new Student("迪迪", 19);
        Student s3 = new Student("倩倩", 19);
        Student s4 = new Student("丽媛", 19);
        Student s5 = new Student("商商", 19);
        c.add(s5);
        c.add(s4);
        c.add(s);
        c.add(s2);
        c.add(s3);
        Object[] o = c.toArray();
        for(int i = 0; i < o.length; i++){
            Student ss = (Student)o[i];
            System.out.println(ss.getName()+"---"+ss.getAge());
        }
    }

}
package cn.itcast_02;

public class Student {
    private String name;
    private int age;
    public Student(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    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;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", age=" + age + "]";
    }
    
}

 

posted on 2016-01-16 16:41  张明明_1  阅读(132)  评论(0编辑  收藏  举报

导航