Javaイテレータ(Iterator)のnext()およびhasNextメソッドの理解


最後に、Javaコレクションイテレータのit.hashNext()メソッドとit.next()メソッド
質問を見つけて、ソースコードに従ってみましょう

	//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,所以此处来看是取得当前元素
       }

結論:イテレータを使用するプロセスでは、it.hasNext()メソッドはポインタの移動を伴わず、現在のポインタが添え字を超えているかどうか、つまり次の要素があるかどうかを判断するだけです。ソースコードのit.next()メソッドは、最初にポインタを下に移動し、現在の要素を取得します。next()メソッドのみが、プロセス全体でポインターを下に移動する必要があります。

おすすめ

転載: blog.csdn.net/qq_38338409/article/details/119430053