设计模式——迭代器模式(Iterator Pattern)

迭代器模式(Iterator Pattern)又称为游标模式,它提供一种顺序访问集合/容器元素的方法,而又无须暴露集合内部表示。本质是抽取集合对象迭代的行为到迭代器中,提供一致的访问接口。属于行为型模式。

适用场景:

  • 访问一个集合对象的内容而无须保留它的内部表示
  • 为遍历不同的集合结构提供一个统一的访问接口
public interface Iterator<E> {
    // 检查是否有下一个元素
    boolean hasNext();
    // 拿到下一个元素
    E next();
    // remove操作,需实现类去实现
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }
}

ArrayList对Iterator的实现

public class ArrayList<E> {
    transient Object[] elementData;
    private int size;
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        public boolean hasNext() {
            return cursor != size;
        }

        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
    }
}

泛型占位符

E: Element, 如果是集合,规定集合元素的类型
T: Type, 规定该类操作的类的具体类型
K: Key, 规定键值对中键的类型
V: Value, 规定键值对中值的类型
?: 任意类型,啥都可以,类似Object

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值