设计模式之迭代器模式

2017-10-31  本文已影响0人  wellong_chen
1.迭代器模式主要为容器服务,实现 next(), hasNext() 方法
public interface Iterator<E> {

    boolean hasNext();

    E next();
    
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

public class ProjectIterator implements Iterator {

    private int currentItem = 0;

    private List list;

    public ProjectIterator(List list) {
        this.list = list;
    }

    public boolean hasNext() {
        if (currentItem == list.size()) {
            return false;
        }
        return true;
    }

    public Object next() {
        if (hasNext()) {
            return list.get(currentItem++);
        }
        return null;
    }
}
上一篇下一篇

猜你喜欢

热点阅读