集合:ListIterator

why ? when ? how ? what ?

Java 集合框架图

有了 Iterator 为什么还要有 ListIterator 呢?

Iterator 遍历的时候如果你想修改集合中的元素怎么办? ListIterator来了。

ListIterator有以下功能:

  1. 可以向两个方向(前、后)遍历 List
  2. 在遍历过程中可以修改 list的元素
  3. 将制定的元素插入列表中

ListIterator 有两种获取方式

  1. List.listIterator()
  2. List.listIterator(int location) //可以指定游标的所在位置

内部实现类源码如下:

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

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

    public E previous() {
        checkForComodification();
        try {
            int i = cursor - 1;
            E previous = get(i);
            lastRet = cursor = i;
            return previous;
        } catch (IndexOutOfBoundsException e) {
            checkForComodification();
            throw new NoSuchElementException();
        }
    }

    public int nextIndex() {
        return cursor;
    }

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

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

        try {
            AbstractList.this.set(lastRet, e);
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    public void add(E e) {
        checkForComodification();

        try {
            int i = cursor;
            AbstractList.this.add(i, e);
            lastRet = -1;
            cursor = i + 1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }
}

参考

https://blog.csdn.net/u011240877/article/details/52752589

posted @ 2018-08-02 14:43  罗贱人  阅读(311)  评论(0编辑  收藏  举报