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

标签 java collections iterator

<分区>

/* 我有一个员工列表 */

List<Employee> empList=new ArrayList<Employee>();
empList.add(employee1);
empList.add(employee2);
empList.add(employee3);
empList.add(employee4);

/* 我取了一个迭代器 */

Iterator<Employee> empIterator=empList.iterator();

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

最佳答案

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

如果您查看 source code你会发现它

 public Iterator<E> iterator() {
     return new Itr();
 }

和类 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();
        }
    }

关于java - Java迭代器如何在内部工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36065361/

相关文章:

java - 按对象的两个字段排序。 java

c# - OOC : What is the difference between ToList() and casting to List<T> in . 网络?

c++ - 基于上下文的 partition_copy

java - 如何在 Android 中发出并处理一个 Http 请求,并给出一个 json 文件作为响应?

java - 使用 Jersey 对 Google Translate 进行 POST 调用会返回 HTTP 404

java - 从 Java 集合中访问元素的速度更快

java - 覆盖迭代器类型

c++ - 将 const_iterator 分配给迭代器

java - 根据当前位置Android从最近到最远对Java中的列表进行排序

java - 如何在android中等待改变不同的imageview?