java迭代器如何在内部工作?

Ven*_*ata 3 java collections iterator

/* 我有一份员工名单 */

List<Employee> empList=new ArrayList<Employee>();
empList.add(employee1);
empList.add(employee2);
empList.add(employee3);
empList.add(employee4);
Run Code Online (Sandbox Code Playgroud)

/* 我采用了一个迭代器 */

Iterator<Employee> empIterator=empList.iterator();
Run Code Online (Sandbox Code Playgroud)

在上面的行中,我试图通过列表获取迭代器。我的疑问是迭代器中会有什么(将所有列表对象复制到其中还是克隆列表对象或......我只是一无所知)。帮助我理解这一点。提前致谢。

Sur*_*tta 6

迭代器将拥有修改底层列表的方法,这里是调用迭代器时返回的内部类

如果你看看source code它,你会发现

 public Iterator<E> iterator() {
     return new Itr();
 }
Run Code Online (Sandbox Code Playgroud)

和班级 Itr

private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return
    int lastRet = -1; // index of last element returned; -1 if no such
    int expectedModCount = modCount;

    public boolean hasNext() {
        return cursor != size;
    }

    @SuppressWarnings("unchecked")
    public E next() {
        checkForComodification();
        int i = cursor;
        if (i >= size)
            throw new NoSuchElementException();
        Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length)
            throw new ConcurrentModificationException();
        cursor = i + 1;
        return (E) elementData[lastRet = i];
    }

    public void remove() {
        if (lastRet < 0)
            throw new IllegalStateException();
        checkForComodification();

        try {
            ArrayList.this.remove(lastRet);
            cursor = lastRet;
            lastRet = -1;
            expectedModCount = modCount;
        } catch (IndexOutOfBoundsException ex) {
            throw new ConcurrentModificationException();
        }
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 好吧,这些评论完全出乎意料。我已经擦洗了它们。提醒一下:请不要因为试图帮助他人而侮辱他人。 (6认同)

Dar*_*oid 5

大多数简单 Java 集合的迭代器仅保留迭代器当前所在集合中位置的指针。调用.next()将推进迭代器。它不会复制元素,而只是返回集合中的下一个元素。由于集合不是克隆或复制的,任何不通过迭代器(包括通过其他迭代器)对集合进行的结构修改(添加或删除元素)都会破坏迭代器,并且尝试使用它很可能会抛出ConcurrentModificationException. 这很简单,内存效率高,并且适合绝大多数用例。

并发集合的迭代器(在java.util.concurrent)要复杂得多,并且特定于每个集合的操作方式,以便在集合发生修改时提供结果。

  • 尽管迭代器并未完成对集合的所有修改,但并非都会导致“ConcurrentModificationException” - 例如,您可以在迭代进行时“设置”一个元素,而不会出现问题。 (3认同)