java迭代器如何在内部工作? [英] How a java iterator works internally?

查看:58
本文介绍了java迭代器如何在内部工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

/* I have a list of employees */

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

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

/* I have taken an iterator */

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

在上一行中,我试图在列表上获得一个迭代器.我的疑问是迭代器中会存在什么(将所有列表对象都复制到其中,还是将克隆列表对象,或者……我只是一无所知).帮助我理解这一点. 预先感谢.

In the above line , I was trying to get an iterator over the list. My doubt is what would be there in the iterator (will all the list objects be copied into it or the list object is cloned or... I'm just clueless). Help me in understanding this. Thanks in advance.

推荐答案

迭代器将具有修改基础列表的方法,这是调用迭代器时返回的内部类

Iterator will be having the methods to modify the underlying list and here is the internal class that returns when you call iterator

如果您查看

If you look at the source code of it you find

 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迭代器如何在内部工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆