225 (案例)集合存储学生对象并遍历
【需求】
创建一个存储学生对象的集合,存储3个学生对象,遍历这个集合。
> 在前两节课的讲解中,用的是字符串类型的集合,现在要用对象类型的集合了
【思路】
1.定义学生类
2.创建Collection集合对象
3.创建学生对象
4.添加学生到集合中
5.遍历集合
--------------------------------------------------------------
(module)myCollection
(package)e225
(class)Student,CollectionDemo
package e225;
--------------------------------------------------------------
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;
}
}
--------------------------------------------------------------
package e225;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
// Collection写完以后变红了,是因为写太快没导包,按悬停后的提示(ctrl shift enter)去做就好了
Collection<Student> c = new ArrayList<Student>();
Student s1 = new Student("Tracy",33);
Student s2 = new Student("Jimmy",22);
Student s3 = new Student("Ben",70);
c.add(s1);
c.add(s2);
c.add(s3);
// 通过集合对象,调用iterator方法,得到迭代器对象
Iterator<Student> it = c.iterator();
while(it.hasNext()){
// 通过迭代器对象的next方法,获取集合的元素
Student s = it.next();
// 输出元素的name变量、age变量
System.out.println(s.getName()+","+s.getAge());
}
}
}
--------------------------------------------------------------
Tracy,33
Jimmy,22
Ben,70