Java8 internal iteration

可紊 提交于 2020-01-12 18:47:19

问题


Does java8 forEach method use an iterator or not really? I google it to the bone, could not find it precisely. Only the fact that it will iterate in the same order the data are.

Any tips?


回答1:


The default implementation of Iterable#forEach is based on a iterator.

    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }

But in ArrayList is overridden to this, and not uses the iterator, it uses a for loop over 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 of its implementation.

Anyway, since this method is declared in Iterable interface, all iterables has this method.



来源:https://stackoverflow.com/questions/30331427/java8-internal-iteration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!