需求:创建一个存储学生类的集合,存储三个学生对象,使用程序实现在控制台编辑该集合
思路:
1.定义学生类
2.创建collection集合
3.创建学生对象
4.把学生添加到集合
5.遍历集合(迭代器方式)
studentDemo(测试类)
package collection集合存储学生对象并遍历;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class studentDmeo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Collection<student> c =new ArrayList<student>();
student s = new student (20,"林青霞");
student s1=new student (18,"哈莉");
student s2=new student (24,"绝代双骄");
c.add(s);
c.add(s1);
c.add(s2);
Iterator<student> it = c.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
student类
package collection集合存储学生对象并遍历;
public class student {
private int age;
private String name;
//--------------------------------
/**
* @param age
* @param name
*/
public student(int age, String name) {
this.age = age;
this.name = name;
}
/**
*
*/
public student() {
}
//--------------------------------------------
/**
* @return age
*/
public int getAge() {
return age;
}
/**
* @param age 要设置的 age
*/
public void setAge(int age) {
this.age = age;
}
/**
* @return name
*/
public String getName() {
return name;
}
/**
* @param name 要设置的 name
*/
public void setName(String name) {
this.name = name;
}
//---------------------------------------------------
@Override
public String toString() {
return "student [age=" + age + ", name=" + name + "]";
}
}