ArrayList 中的 forEachRemaining方法是做什么的?

我正在研究 ArrayList 实现并找到了 forEachRemaining 方法。这个或者什么时候调用这个方法有什么用?


public class ArrayList<E> extends AbstractList<E>

        implements List<E>, RandomAccess, Cloneable, java.io.Serializable

{

    //...

    //...

    private class Itr implements Iterator<E> {

        //...


        @Override

        @SuppressWarnings("unchecked")

        public void forEachRemaining(Consumer<? super E> consumer) {

            Objects.requireNonNull(consumer);

            final int size = ArrayList.this.size;

            int i = cursor;

            if (i >= size) {

                return;

            }

            final Object[] elementData = ArrayList.this.elementData;

            if (i >= elementData.length) {

                throw new ConcurrentModificationException();

            }

            while (i != size && modCount == expectedModCount) {

                consumer.accept((E) elementData[i++]);

            }

            // update once at end of iteration to reduce heap write traffic

            cursor = i;

            lastRet = i - 1;

            checkForComodification();

        }

    }

}


呼如林
浏览 668回答 2
2回答

幕布斯6054654

ArrayList没有forEachRemaining,迭代器等它返回做。从文档中Iterator:对每个剩余元素执行给定的操作,直到处理完所有元素或操作引发异常。如果指定了该顺序,则操作按迭代顺序执行。动作抛出的异常被转发给调用者。

汪汪一只猫

如果使用迭代器遍历列表,next()则它将返回该列表中的下一个元素。因此,假设您没有遍历完整列表并调用forEachRemaining()它,那么它将列表中未遍历的剩余元素。演示List<String> list = new ArrayList<>();list.add("one");list.add("two");list.add("three");list.add("four");list.add("five");//added five element in listIterator<String> iterator =&nbsp; list.iterator();//visiting two elements by called next()System.out.println("Printed by next():" + iterator.next());System.out.println("Printed by next():" + iterator.next());//remaining un-visited elements can be accessed using forEachRemaining()iterator.forEachRemaining(s -> {System.out.println( "Printed by forEachRemaining():" + s);});输出:Printed by next():onePrinted by next():twoPrinted by forEachRemaining():threePrinted by forEachRemaining():fourPrinted by forEachRemaining():five
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java