Java8内部迭代 [英] Java8 internal iteration

查看:128
本文介绍了Java8内部迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

java8 forEach方法是否真的使用迭代器?我把它谷歌到骨头,找不到它。只是它会以相同的顺序迭代数据。

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.

任何提示?

推荐答案

Iterable#forEach的默认实现基于迭代器。

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);
        }
    }

但是在ArrayList中重写了这个,而不是使用迭代器,它在其内部数组上使用for循环

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.

无论如何,由于此方法是在Iterable接口中声明的,因此所有迭代都使用此方法。

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

这篇关于Java8内部迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆