创建一个学生对象集合,存储几个学生对象,使用程序实现遍历集合,结果输出到控制台
学生类:
/**
* @author Wrry
* @data 2020
* @desc 学生类
*/
public class Student {
private String name;
private String age;
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public Student(String name, String age) {
this.name = name;
this.age = age;
}
public Student() {
}
}
测试类:
/**
* @author Wrry
* @data 2020
* @desc 创建一个学生对象集合,存储几个学生对象,使用程序实现遍历集合,结果输出到控制台
*
* 思路:
* 1.定义学生类
* 2.创建Collection集合
* 3.创建学生对象
* 4.把学生对象添加到集合当中去
* 5.遍历集合(利用迭代器遍历)
*/
public class Collection03 {
public static void main(String[] args) {
//创建Collection集合
Collection<Student> c = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("小白", "22");
Student s2 = new Student("小黑", "23");
Student s3 = new Student("小w", "25");
//把学生信息添加到集合
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);
}
}
}