分别用Collection,List,ArrayList装入自定义学生类,并输出
测试类
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import com.ma.bean.Student; /** * 测试类 * @author ma * */ public class CollectionDemo8 { /* * 需求:用集合存储五个学生对象,并遍历学生对象,分别用: * 1.用Collection 来做 * 2.用List来做 * 3.用ArrayList来做 * * 分析: * 1.创建一个集合 * 2.创建 一个学习类Student * 3.把学习对象放入集合中 * 4.遍历集合,得到学习对象 * 5.输出学习信息 * */ public static void main(String[] args) { //1.用Collection 来做 //创建 一个Collection Collection<Student> c = new ArrayList<Student>(); //创建学生对象 Student s1 = new Student("曹操" ,1); Student s2 = new Student("刘备" ,2); Student s3 = new Student("关羽" ,3); Student s4 = new Student("张飞" ,4); Student s5 = new Student("赵云" ,5); //添加数据 c.add(s1); c.add(s2); c.add(s3); c.add(s4); c.add(s5); //遍历输出 getStudent(c); /* * 输出结果: * 姓名:曹操 年龄 :1岁 * 姓名:刘备 年龄 :2岁 * 姓名:关羽 年龄 :3岁 * 姓名:张飞 年龄 :4岁 * 姓名:赵云 年龄 :5岁 */ //2.用List来做 //创建一个list List list = new ArrayList(); //创建学生对象 Student s11 = new Student("曹操" ,11); Student s21 = new Student("刘备" ,21); Student s31 = new Student("关羽" ,31); Student s41 = new Student("张飞" ,41); Student s51 = new Student("赵云" ,51); list.add(s11); list.add(s21); list.add(s31); list.add(s41); list.add(s51); //遍历输出 getStudent(list); /* * 输出结果: * 姓名:曹操 年龄 :11岁 * 姓名:刘备 年龄 :21岁 * 姓名:关羽 年龄 :31岁 * 姓名:张飞 年龄 :41岁 * 姓名:赵云 年龄 :51岁 */ //3.用ArrayList来做 //创建一个ArrayList ArrayList arrList = new ArrayList(); //创建学生对象 Student s111 = new Student("曹操" ,111); Student s211 = new Student("刘备" ,211); Student s311 = new Student("关羽" ,311); Student s411 = new Student("张飞" ,411); Student s511 = new Student("赵云" ,511); arrList.add(s111); arrList.add(s211); arrList.add(s311); arrList.add(s411); arrList.add(s511); //输出 getStudent(arrList); /* * 输出结果: * 姓名:曹操 年龄 :111岁 * 姓名:刘备 年龄 :211岁 * 姓名:关羽 年龄 :311岁 * 姓名:张飞 年龄 :411岁 * 姓名:赵云 年龄 :511岁 */ } /** * 输出集合中学生对象的信息 * @param c 要遍历的集合 * */ public static void getStudent(Collection c){ //得到迭代器 Iterator<Student> it = c.iterator(); //遍历输出 while (it.hasNext()) { Student student = (Student) it.next(); System.out.println("姓名:"+student.getName()+" 年龄 :"+student.getAge()+"岁"); } } }
学生类
package com.ma.bean; /** * 学生类 * @author ma * */ public class Student { //成员变量 //姓名 String name; //年龄 int age; //无参构造方法 public Student() { super(); } //有参构造方法 public Student(String name, int age) { super(); this.name = name; this.age = age; } //get() 和 set() 方法 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; } //重写toString()方法 @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } }