Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Java 集合源碼解析:ListIterator 雙向迭代器完全指南

編輯:關於 Android 程式設計

ListIterator

根据官方文档介绍,ListIterator 有以下功能:

允许我们向前、向后两个方向遍历 List;在遍历时修改 List 的元素;遍历时获取迭代器当前游标所在的位置。

关于游标(cursor)

注意,迭代器没有「当前所在元素」一说,它只有一个游标(cursor)的概念,这个游标总是在元素之间,比如这样:

初始时它在第 0 个元素之前,调用 next() 游标后移一位:

调用 previous() 游标就会回到之前位置。当向后遍历完元素,游标就会在元素 N 的后面:

也就是说,长度为 N 的集合会有 N+1 个游标的位置。


ListIterator 继承自 Iterator 接口

ListIterator 在 Iterator 的基础上增加了 6 个方法:

介绍一下新增加的几个方法

void hasPrevious():判断游标前面是否有元素。

Object previous():返回游标前面的元素,同时游标前移一位。游标前没有元素就报 java.util.NoSuchElementException 错,所以使用前最好判断一下。

int nextIndex():返回游标后边元素的索引位置,初始为 0;遍历 N 个元素结束时为 N。

int previousIndex():返回游标前面元素的位置,初始时为 -1。

void add(E):在游标前面插入一个元素。注意,是前面。

void set(E):更新迭代器最后一次操作的元素为 E,也就是更新最后一次调用 next() 或 previous() 返回的元素。注意,当没有迭代(没有调用 next() 或 previous())就直接调用 set 时,会报 java.lang.IllegalStateException 错。

void remove():删除迭代器最后一次操作的元素,注意事项和 set 一样。

ListIterator 的两种获取方式

List.listIterator()
List.listIterator(int location)

区别在于第二种可以指定游标所在的位置。

ListIterator 的具体实现

AbstractList 作为 List 的直接子类,里面实现了 listIterator() 方法,并且有两个内部迭代器实现类:SimpleListIterator 和 FullListIterator:

listIterator() 返回的是 FullListIterator():

FullListIterator 继承了 SimpleListIterator,SimpleListIterator 实现了 Iterator 接口:

private class SimpleListIterator implements Iterator<E> {
    // 游标的位置,初始为 -1
    int pos = -1;
    // 用来判断是否 fail-fast 的变量
    int expectedModCount;
    // 记录上次迭代的位置
    int lastPosition = -1;

    SimpleListIterator() {
        expectedModCount = modCount;
    }

    // 当游标没有跑到最后一个元素后面时 hasNext 返回 true
    public boolean hasNext() {
        return pos + 1 < size();
    }

    // 获取下一个元素
    public E next() {
        if (expectedModCount == modCount) {
            try {
                E result = get(pos + 1);
                lastPosition = ++pos;
                return result;
            } catch (IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
        }
        // 迭代时修改元素就会报这个错
        throw new ConcurrentModificationException();
    }

    // 删除上次迭代操作的元素
    public void remove() {
        if (this.lastPosition == -1) {
            throw new IllegalStateException();
        }
        if (expectedModCount != modCount) {
            throw new ConcurrentModificationException();
        }
        try {
            AbstractList.this.remove(lastPosition);
        } catch (IndexOutOfBoundsException e) {
            throw new ConcurrentModificationException();
        }
        expectedModCount = modCount;
        if (pos == lastPosition) {
            pos--;
        }
        // 每次删除后都还原为 -1,说明迭代一次后只能 remove 一次
        lastPosition = -1;
    }
}

了解了 SimpleListIterator 后,看下 FullListIterator 的具体实现:

private final class FullListIterator extends SimpleListIterator implements ListIterator<E> {
    // 根据 start 指定游标位置
    FullListIterator(int start) {
        if (start >= 0 && start <= size()) {
            pos = start - 1;
        } else {
            throw new IndexOutOfBoundsException();
        }
    }

    // 在游标前面添加元素
    public void add(E object) {
        if (expectedModCount == modCount) {
            try {
                AbstractList.this.add(pos + 1, object);
            } catch (IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
            pos++;
            // 注意!添加后上次迭代位置又变回 -1,说明 add 后调用 remove、set 会有问题
            lastPosition = -1;
            if (modCount != expectedModCount) {
                expectedModCount = modCount;
            }
        } else {
            throw new ConcurrentModificationException();
        }
    }

    // 当游标不在初始位置(-1)时返回 true
    public boolean hasPrevious() {
        return pos >= 0;
    }

    // 游标后面的元素索引,就是游标 +1
    public int nextIndex() {
        return pos + 1;
    }

    // 游标前面一个元素
    public E previous() {
        if (expectedModCount == modCount) {
            try {
                E result = get(pos);
                lastPosition = pos;
                pos--;
                return result;
            } catch (IndexOutOfBoundsException e) {
                throw new NoSuchElementException();
            }
        }
        throw new ConcurrentModificationException();
    }

    // 游标前面元素的索引,就是游标的位置
    public int previousIndex() {
        return pos;
    }

    // 更新之前迭代的元素为 object
    public void set(E object) {
        if (expectedModCount == modCount) {
            try {
                AbstractList.this.set(lastPosition, object);
            } catch (IndexOutOfBoundsException e) {
                throw new IllegalStateException();
            }
        } else {
            throw new ConcurrentModificationException();
        }
    }
}

可以看到 SimpleListIterator 的主要操作最后都交给子类来实现。List 的子类 ArrayList、LinkedList、Vector 由于底层实现原理不同(数组、双向链表),具体操作方法实现也有所不同。等后续分析到具体子类时再看相关实现。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved