迭代器模式提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。提供一种方法顺序访问一个聚合对象中的各种元素,而又不暴露该对象的内部表示。访问一个聚合对象的内容而无需暴露它的内部表示
支持对聚合对象的多种遍历,为遍历不同的聚合结构提供一个统一的接口。
迭代器模式可以直接使用原生 JDK 中提供的方法:java.util.Iterator;,如:
- import java.util.ArrayList;
- import java.util.Iterator;
- /** * 原生的迭代器用法 */
- public class UtilIteratorTest {
- public static void main(String[] args) { // TODO 自动生成的方法存根ArrayList<string> array = new ArrayList<string>();array.add("a");array.add("b");array.add("c");array.add("d");Iterator<string> it = array.iterator();while(it.hasNext()){System.out.println(it.next());}}}
也可自定义 MyIterator 实现:
Iterator:自定义迭代器接口
- public interface Iterator { // 前移public Object previous();// 后移public Object next();// 是否还有下个元素public boolean hasNext();// 取得第一个元素public Object first();}
Collection:定义一个用来处理集合接口
- public interface Collection {
- public Iterator iterator();
- /* 取得集合元素 */
- public Object get(int i);
- /* 取得集合大小 */
- public int size();
- }
MyIterator:实现迭代器接口
- public class MyIterator implements Iterator {
- private Collection collection;
- private int pos = -1;
- public MyIterator(Collection collection) {
- this.collection = collection;
- }@Override public Object previous() {
- if (pos > 0) {
- pos--;
- }
- return collection.get(pos);
- }@Override public Object next() {
- if (pos < collection.size() - 1) {
- pos++;
- }
- return collection.get(pos);
- }@Override public boolean hasNext() {
- if (pos < collection.size() - 1) {
- return true;
- } else {
- return false;
- }
- }@Override public Object first() {
- pos = 0;
- return collection.get(pos);
- }
- }
MyCollection:实现该集合接口
- public class MyCollection implements Collection {
- public String[] string = {};
- public MyCollection(String[] array) {
- string = array;
- }@Override public Iterator iterator() {
- return new MyIterator(this);
- }@Override public Object get(int i) {
- return string[i];
- }@Override public int size() {
- return string.length;
- }
- }
执行过程:
- String[] array = {
- "A",
- "B",
- "C",
- "D",
- "E"
- };
- Collection collection = new MyCollection(array);
- Iterator it = collection.iterator();
- while (it.hasNext()) {
- System.out.println(it.next());
- }
执行结果:
- A B C D E
就爱阅读 www.92to.com 网友整理上传, 为您提供最全的知识大全, 期待您的分享,转载请注明出处。
来源: