2 回答

TA貢獻1876條經驗 獲得超7個贊
ArrayList
沒有forEachRemaining
,迭代器等它返回做。
對每個剩余元素執行給定的操作,直到處理完所有元素或操作引發異常。如果指定了該順序,則操作按迭代順序執行。動作拋出的異常被轉發給調用者。

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
添加回答
舉報