package com.zhiwei.iterator;public interface Container { public void add(Object obj); public void remove(Object obj); public Iterator iterator();}
具体容器角色:ConcreteContainer
package com.zhiwei.iterator;import java.util.ArrayList;import java.util.List;public class ConcreteContainer implements Container { private List
迭代器角色:Iterator
package com.zhiwei.iterator;public interface Iterator { public Object next(); public boolean hasNext();}
具体迭代器角色:ConcreteIterator
package com.zhiwei.iterator;import java.util.ArrayList;import java.util.List;public class ConcreteIterator implements Iterator { private List list = new ArrayList(); private int cursor = 0; /** * 迭代器关联具体的容器类 * @param list */ public ConcreteIterator(List list) { this.list = list; } /** * 判断容器是否还有下一个元素 */ public boolean hasNext() { if (cursor == list.size()) { return false; } return true; } /** * 获取容器下一个元素 */ public Object next() { Object obj = null; if (this.hasNext()) { obj = this.list.get(cursor++); //保存游标位置 } return obj; }}
测试代码:
Container container = new ConcreteContainer();container.add("小明");container.add("小红");container.add("小刚");//获取迭代器:容器对象和迭代器对象已经关联Iterator it = container.iterator(); while (it.hasNext()) {String str = (String) it.next();System.out.println(str);}