分享

Collection遍历之iterator迭代器遍历

 樱花梦_张艺馨 2016-11-23
=========练习:用集合存储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


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多