Understanding of next() and hasNext methods of Java iterator (Iterator)


Regarding the it.hashNext() and it.next () methods in java collection iterators ) method in the end is to get the current element and move the pointer down or directly get the next element?
Let's find a question and follow the source code

	//jdk1.8
    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;
       }

       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];//lastRet初始值为-1,所以此处来看是取得当前元素
       }

Conclusion : In the process of using the iterator, the it.hasNext() method does not involve the movement of the pointer, but only determines whether the current pointer exceeds the subscript, that is, whether there is a next element. The it.next() method from the source code first moves the pointer down and gets the current element. Only the next() method involves moving the pointer down in the whole process.

Guess you like

Origin blog.csdn.net/qq_38338409/article/details/119430053