=========练习:用集合存储5个学生对象,并吧学生对象进行遍历===== ========Student类:====== package com.gc.action; public class Student { private String name; private int age; public Student() { super(); } public Student(String name, int age) { super(); this.name = name; this.age = age; } // getXxx/setXxx public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ==========StudentTest类======== package com.gc.test; import java.util.ArrayList; import java.util.Collection; import com.gc.action.Student; public class StudentTest { public static void main(String[] args) { Collection c =new ArrayList(); Student s1 =new Student("zyx1",21); Student s2 =new Student("zyx2",22); Student s3 =new Student("zyx3",23); Student s4 =new Student("zyx4",24); Student s5 =new Student("zyx5",25); c.add(s1); c.add(s2); c.add(s3); c.add(s4); c.add(s5); Object[] obj = c.toArray(); for (int i = 0; i < obj.length; i++) { Student s = (Student) obj[i]; System.out.println(s.getName()+"---"+s.getAge()); } } } 结果: zyx1---21 zyx2---22 zyx3---23 zyx4---24 zyx5---25 ===============iterator方法============ package com.gc.test; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class StudentTest { public static void main(String[] args) { Collection c =new ArrayList(); c.add("zyx1"); c.add("zyx2"); c.add("zyx3"); c.add("zyx4"); c.add("zyx5"); Iterator it = c.iterator(); while (it.hasNext()) { //判断是否存在下一个,存在就遍历 System.out.println(it.next()); } } } 结果: zyx1
zyx2 zyx3 zyx4 zyx5 |
|