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;
}
}
网友评论