Java8 internal iteration

Does the java8 forEach method use an iterator or not? I google it to the bone, could not find it for sure. Just the fact that it will iterate in the same order as the data.

Any tips?

+7
java-8 java-stream
source share
1 answer

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.

+12
source share

All Articles