集合: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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章