ArrayList ListItr

为什么80%的码农都做不了架构师?>>>   hot3.png

首先ListItr实现了ListIterator接口并继承了Itr,也就说明了ListItr具备ListIterator的所有功能。 ListIterator是Iterator的子类,它只能用于List类的访问。Iterator只能单向移动,而ListIterator可以双向移动,而且还拥有了set和add功能。 ListItr还允许你从数组的任意位置开始迭代。 以下是ListItr的源码:

private class ListItr extends Itr implements ListIterator {
        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();
            }
        }
    }

转载于:https://my.oschina.net/antin/blog/704491

你可能感兴趣的:(ArrayList ListItr)