java迭代器内部是如何工作的? [关闭]

2024-05-19

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

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 http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b27/java/util/ArrayList.java#ArrayList.iterator%28%29你发现其中

 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();
        }
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java迭代器内部是如何工作的? [关闭] 的相关文章

随机推荐