亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

呼如林 2021-10-20 16:06:45
我正在研究 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();        }    }}
查看完整描述

2 回答

?
幕布斯6054654

TA貢獻1876條經驗 獲得超7個贊

ArrayList沒有forEachRemaining,迭代器等它返回做。

文檔中Iterator

對每個剩余元素執行給定的操作,直到處理完所有元素或操作引發異常。如果指定了該順序,則操作按迭代順序執行。動作拋出的異常被轉發給調用者。


查看完整回答
反對 回復 2021-10-20
?
汪汪一只貓

TA貢獻1898條經驗 獲得超8個贊

如果使用迭代器遍歷列表,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 list


Iterator<String> iterator =  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():one

Printed by next():two

Printed by forEachRemaining():three

Printed by forEachRemaining():four

Printed by forEachRemaining():five


查看完整回答
反對 回復 2021-10-20
  • 2 回答
  • 0 關注
  • 704 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號