Java迭代器(Iterator)的next()及hasNext方法的理解

关于java集合迭代器中的it.hashNext()和it.next()方法
今天突然想了一下找个问题,网上大多数说是直接取下一个元素,很迷惑,那么迭代器中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
今日推荐