我正在研究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();
}
}
}
答案 0 :(得分:0)
ArrayList
没有forEachRemaining
,迭代器等返回了。
来自the documentation for Iterator
:
对每个剩余元素执行给定的操作,直到所有元素都已处理或该操作引发异常。如果指定了顺序,则按照迭代顺序执行操作。该操作引发的异常会中继到调用方。
答案 1 :(得分:0)
如果使用next()
在列表上遍历,则使用Iterator,它将返回该列表中的下一个元素。因此,假设您没有遍历完整列表并调用了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