程序员

Iterator理解

2017-11-24  本文已影响58人  icecrea

迭代器(Iterator):迭代的意思是说,为了逼近所需目标或结果,每一次对过程的重复称为一次“迭代”,而每一次迭代得到的结果会作为下一次迭代的初始值。而迭代器则是类似于可移动的标记,用于标记某一次迭代,实现迭代的过程。在Java中,使用迭代器来实现遍历集合类对象。

可迭代的(Iterable):故名思议,实现了这个接口的集合对象支持迭代,是可迭代的。able结尾的表示 能...样,可以做...。

Collection接口继承了Iterable接口,实现Collection接口的类可以进行迭代,Map没有继承Collection接口,无法迭代。而实现Iterable接口,就必须实现Iterable中的Iterator iterator()方法

对于arraylist,它有内部类Itr实现了Iterator接口

    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();
        }
    }

Itr类中定义了cursor,lastRet,expectedModCount三个变量。
cursor代表了当前位置下一个的计数。也就是说当判断hasNext()时候,是判断cursor是否等于size
lastRet代表了前一个返回的位置计数。我认为看成当前更容易理解。每次next方法时,判断是cursor是否大于等于size,判断cursor是否大于elementData.length,最后cursor++,然后lastRet=当前元素位置,返回当前元素。

ListIterator 和 Iterator不同点

  1. 使用范围不同,Iterator可以应用于所有的集合,Set、List和Map和这些集合的子类型。而ListIterator只能用于List及其子类型。
  2. ListIterator有add方法,可以向List中添加对象,而Iterator不能。
  3. ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator不可以。
  4. ListIterator可以定位当前索引的位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。
  5. 都可实现删除操作,但是ListIterator可以实现对象的修改,set()方法可以实现。Iterator仅能遍历,不能修改。
上一篇 下一篇

猜你喜欢

热点阅读