java基础-迭代器模式

我们首先来看维基百科的解释,迭代器模式是一种设计模式,是一种最简单也最常见的设计模式。它可以让使用者透过特定的接口遍历容器中的每一个元素而不用了解底层的运作情况。

在java中存在两个接口
public interface Iterator<E>

以及它的子接口
public interface ListIterator<E>


我们以ArrayList为例,观察一下她的实现,以下是迭代器的核心代码
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;
    }

    @SuppressWarnings("unchecked")
    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();
        }
     }
      // 检查并发的修改 由于整个迭代器就不是线程安全的,所以这个并不可靠
     final void checkForComodification() {
                if (modCount != expectedModCount)
                   throw new ConcurrentModificationException();
                }
     }
}

private class ListItr extends Itr implements ListIterator<E> {
      ListItr(int index) {
         super();
         cursor = index;
      }

       public boolean hasPrevious() {
          return cursor != 0;
       }

        public int nextIndex() {
           return cursor;
        }

         public int previousIndex() {
             return cursor - 1;
         }

         @SuppressWarnings("unchecked")
         public E previous() {
             checkForComodification();
             int i = cursor - 1;
             if (i < 0)
                 throw new NoSuchElementException();
             Object[] elementData = ArrayList.this.elementData;
             if (i >= elementData.length)
                throw new ConcurrentModificationException();
              cursor = i;
              return (E) elementData[lastRet = i];
        }

         public void set(E e) {
              if (lastRet < 0)
                 throw new IllegalStateException();
                 checkForComodification();

               try {
                     ArrayList.this.set(lastRet, e);
               } catch (IndexOutOfBoundsException ex) {
                     throw new ConcurrentModificationException();
               }
          }

          public void add(E e) {
               checkForComodification();
               try {
                  int i = cursor;
                  ArrayList.this.add(i, e);
                  cursor = i + 1;
                  lastRet = -1;
                  expectedModCount = modCount;
               } catch (IndexOutOfBoundsException ex) {
                  throw new ConcurrentModificationException();
               }
           }
}
代码中出现了我们熟悉的单词cursor,索引,对就是它,这个数组序列的迭代器就可以想象成在一组数据列表中来回移动,检索。抛开checkForComodification();检查并发修改数据结构的检查外,整个的迭代机制并不神秘。

迭代器模式抽象出了几个概念,第一个 最后一个 上一个 下一个 有没有元素,想象一下我们在火车站排队买票,售票员面对整个队伍可不会报出第一个 第二个。。。,而是常说下一个,因为对于她来说每个元素的位置对她来说可以忽略,她只需要处理当前元素,处理下一个元素,当然上一个处理出错,她也会说上一个,比如我找错钱了,而不会记住说第n个出错,没必要 也不需要。

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值