The Iterable # forEach implementation is based on an iterator by default.
default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } }
But in ArrayList it is redefined and does not use an iterator, it uses a for loop through its internal array
@Override public void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int size = this.size; for (int i=0; modCount == expectedModCount && i < size; i++) { action.accept(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } }
So it depends on its implementation.
In any case, since this method is declared in the Iterable interface, all these iterations have this method.
Ezequiel
source share