浏览 4211 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2011-01-11
MainTest package org.hx.itr; import java.util.Iterator; import java.util.UUID; public class MainTest { public static void main(String[] args) { Dept dept = randomDept(3); for (Staff staff : dept) { System.out.println(staff); } System.out.println(); for (Iterator<Staff> iterator = dept.iterator(); iterator.hasNext();) { Staff staff = iterator.next(); System.out.println(staff); } } /** * 随机产生一些数据用作测试 * @param staffCount * @return */ private static Dept randomDept(int staffCount){ Dept dept = new Dept(); for (int i = 0; i < staffCount; i++) { Staff staff = new Staff(); staff.setName(UUID.randomUUID().toString().substring(0,5)); staff.setGender((int)Math.round(Math.random()*2)); staff.setAge((int)Math.round(Math.random()*100)+1); dept.addStaff(staff); } return dept; } } Dept类:实现了iterable接口 package org.hx.itr; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Dept implements Iterable<Staff> { List<Staff> staffList = new ArrayList<Staff>(); public void addStaff(Staff staff) { this.staffList.add(staff); } public List<Staff> getStaffList() { return staffList; } public Iterator<Staff> iterator() { Itr itr = new Itr(); itr.setDept(this); return itr; } } class Itr implements Iterator<Staff> { private int cursor = -1; private Dept dept; public void setDept(Dept dept) { this.dept = dept; } public boolean hasNext() { return dept.getStaffList() != null && dept.getStaffList().size() > cursor + 1; } public Staff next() { return dept.getStaffList().get(++cursor); } public void remove() { dept.getStaffList().remove(cursor); } } Staff类 package org.hx.itr; public class Staff { private String name; private int gender; private int age; @Override public String toString() { return "name = " + name + ", gender = " + gender + ", age = " + age; } // ...getter and setters... } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |