迭代器模式

来源:互联网 发布:php网站短信接口价格 编辑:程序博客网 时间:2024/05/29 02:32

2 定义
它提供一种方法访问一个容器对象中各个元素,而不需要暴露该对象的内部细节。
Iterator接口
这里写图片描述

3 应用
使用增强的for循环,需要实现Iterable接口,实现iterator()方法,返回一个Iterator。
这里写图片描述
容器类都提供了迭代器。

4 例子

package javazongjie;import java.util.Iterator;import java.util.Vector;public class MyIterator implements Iterator<String>{    private Vector vector = new Vector();    private int cursor = 0;    public MyIterator(Vector vector) {        super();        this.vector = vector;    }    @Override    public boolean hasNext() {        if(this.cursor == this.vector.size()) {            return false;        }        return true;    }    @Override    public String next() {        String result = null;        if(this.hasNext()){            result = (String) this.vector.get(this.cursor++);        }        return result;    }}
package javazongjie;import java.util.Iterator;import java.util.Vector;public class MyCollection implements Iterable<String>{    private Vector<String> vector = new Vector<>();    public boolean add(String s) {        vector.add(s);        return true;    }    @Override    public Iterator<String> iterator() {        return new MyIterator(this.vector);    }}
package javazongjie;public class MyCollectionTest {    public static void main(String[] args) {        MyCollection myCollection = new MyCollection();        myCollection.add("Hello");        myCollection.add("Iterator!");        for(String s : myCollection) {            System.out.print(s + " ");        }        //输出Hello Iterator!     }}
0 0
原创粉丝点击