java collection 对象 arraylist

package jihedemo;

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

/**
 * 需求:
 * 创建collection集合对象
 * 创建学生对象
 * 把学生添加到集合
 * 遍历集合 迭代器方式
 */
public class Demo {
    public static void main(String[] args) {
        // 创建collection 对象
        Collection<Student> c = new ArrayList<Student>();

        Student s1 = new Student("林青霞",30);
        Student s2 = new Student("张曼玉",35);
        Student s3 = new Student("王祖贤",33);


        // 创建学生对象
        c.add(s1);
        c.add(s2);
        c.add(s3);

        // 遍历集合 迭代器方式
        Iterator<Student> it = c.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName()+","+s.getAge());
        }

    }
}
package jihedemo;

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

    public Student() {
    }

    public Student(String name, int age) {
        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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_34608447/article/details/113825643