迭代器的产生是为了以一种统一的方式遍历不同的容器,并且不会暴露内部细节。
public interface IContainer { /** * 长度 * * @return */ int size(); /** * 增 0有效 * * @param data */ void put(Object data); /** * 删 0有效 */ void delete(int position); /** * 改 0有效 * * @param position * @param data */ void set(int position, Object data); /** * 查 0有效 * * @param position * @return */ Object get(int position); /** * 获取迭代器对象 * * @return */ Iterator getIterator();}
public class ListIterator implements Iterator { private IContainer IContainer; private int iteratorPosition; // 当前位置 public ListIterator(IContainer IContainer) { this.IContainer = IContainer; iteratorPosition = 0; } @Override public boolean hasNext() { return iteratorPosition + 1 > IContainer.size(); } @Override public Object next() { iteratorPosition++; return IContainer.get(iteratorPosition); }}
public class ListContainer implements IContainer { private int currentSize = 0; // 元素个数 private Object[] arr; private static int MAX = 100; public ListContainer() { currentSize = 0; arr = new Object[MAX]; } @Override public int size() { return currentSize; } @Override public void put(Object data) { if (data == null) return; if (currentSize >= MAX) return; // 暂时不考虑扩容的问题 arr[currentSize] = data; currentSize++; } @Override public void delete(int position) { if (position < 0 || currentSize == 0 || position >= currentSize) return; if (currentSize > 1) { for (int i = position; i < currentSize - 1; i++) { arr[i] = arr[i + 1]; } } currentSize--; } @Override public void set(int position, Object data) { if (position < 0 || position >= currentSize || data == null) return; arr[position] = data; } @Override public Object get(int position) { return arr[position]; } @Override public Iterator getIterator() { return new ListIterator(this); }}
// 实现
public static void main(String[] args) { IContainer IContainer = new ListContainer(); IContainer.put("1"); IContainer.put("2"); IContainer.put("3"); Iterator iterator = IContainer.getIterator(); while (iterator.hasNext()) { System.out.print(iterator.toString()); }}