Java ListIterator与iterator的区别

在上一篇中 http://gaofulai1988.iteye.com/blog/2261505介绍了ArrayList iterator的实现,今天再分析另外一个list中特有的迭代器ListIterator。

看看它是如何new的呢。

public ListIterator<E> listIterator() {
        return new ListItr(0);
}

 public ListIterator<E> listIterator(int index) {
        if (index < 0 || index > size)
            throw new IndexOutOfBoundsException("Index: "+index);
        return new ListItr(index);
}


又出现了一个内部类,看看它是怎样实现的。

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


总体的代码不难看懂。现在总结一下,它们之间的区别。

1. iterator只能向后遍历,而ListIterator可以向前,也可以向后。
2. ListIterator可以增加元素,但iterator没有。

猜你喜欢

转载自gaofulai1988.iteye.com/blog/2261508
今日推荐