迭代器模式Iterator

什么是迭代器

  迭代器模式提供一种可以让我们在不知道对象内部情况下,可以对该对象进行顺序访问的方法。

java API中的迭代器

1 public interface Iterator<E> {
2     boolean hasNext();
3 
4     E next();
5 
6     void remove(); 
7 }

  hasNext()判断集合中是否还有下一个元素,即判断集合是否已经遍历完。

  next()返回集合中的下一个元素。

  remove()删除刚返回的元素,只能在在next()方法执行后执行。

迭代器的使用

 1 public static void main(String[] args) {
 2         List list = new ArrayList();
 3 
 4         list.add("小明");
 5         list.add("小红");
 6         list.add("小兰");
 7 
 8         Iterator iterator = list.iterator();
 9 
10         while (iterator.hasNext()){
11             System.out.println(iterator.next());
12         }
13     }

java集合中的迭代器

  来看一下java集合ArrayList中对迭代器的实现。

public Iterator<E> iterator() {
        return new Itr();
}
private class Itr implements Iterator<E> {
        int cursor;       
        int lastRet = -1; 
        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();
            }
        }
        

  hasNext()如果当前位置比集合的size小则返回true。

  next()首先判断是否越界,如果next的元素在集合内,则返回该元素。注意:返回的元素位置为lastRet = i。

  remove()第一步判断lastRet是否小于0,只有在next方法执行lastRet = i时才继续运行。

 总的来说,java所以容器都有自己的迭代器。如果我们想实现自己的容器,也需要为这个容器写一个迭代器。

 最后Iterable是可迭代的,java每个集合都实现了这个接口。

posted @ 2017-12-18 21:54  tryinglove  阅读(137)  评论(0编辑  收藏  举报