论坛首页 Java企业应用论坛

实现for each,通过iterable接口和iterator(实例)

浏览 4214 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-01-11  
    java1.5提供了for each的循环方式,实现iterable接口就能让自己的类也能这么来循环,写一个例子。

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...
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics