How a java iterator works internally? [closed]

你。 提交于 2021-02-19 06:00:09

问题


/* 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.


回答1:


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

And the class 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();
        }
    }



回答2:


The iterator for most simple java collections just keeps a pointer of where in the collection the iterator is currently at. Calling .next() will advance the iterator. It doesn't copy the elements, and just returns the next element from the collection. Since the collection is not cloned or copied, any structural modifications (adding or removing elements) made to the collection not through the iterator (including through other iterators) will break the iterator, and trying to use it will very likely throw a ConcurrentModificationException. This is simple, memory-efficent, and suitable for the vast majority of use-cases.

Iterators for the concurrent collections (in java.util.concurrent) are far more complex, and are specific to each collection in how they operate in order to provide results in the face of modifications happening to the collection.



来源:https://stackoverflow.com/questions/36065361/how-a-java-iterator-works-internally

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!