该接口是集合类的最顶层接口,其字面意义是可以迭代的意思,可以理解为实现这个接口的集合类获得了迭代遍历的能力。
Iterable
接口出现在 JDK1.5,只有iterator()
一个方法,该方法返回一个迭代器实例引用,用于遍历当前集合实现类。此时Iterable接口此时定义了一种遍历集合的规范,即可使用迭代器遍历集合。同时,该接口的集合实现类也可以使用for-each遍历集合,但这只是一种语法糖,在经过编译之后产生的class文件中,for-each语句会转化为基于迭代器的遍历方式。
在JDk1.8中,Iterable
接口添加了forEach()
方法和spliterator()
方法,这两个方法都基于基于JDK1.8的Consumer类。
forEach()
方法为每一个集合元素执行指定动作。spliterator()
方法返回并行遍历迭代器Spliterator接口实现类的应用。该迭代器可并行遍历数据,能够发挥现代处理器的多核优势。
Jdk1.8源码如下
package java.lang;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.Consumer;
/**
* Implementing this interface allows an object to be the target of
* the "for-each loop" statement.
* 实现该接口允许使用for-each语句遍历集合实现类
* @param <T> the type of elements returned by the iterator
* @since 1.5
* @jls 14.14.2 The enhanced for statement 增强for循环
*/
public interface Iterable<T> {
/**
* Returns an iterator over elements of type {@code T}.
* 返回一个类型元素对应的迭代器
*/
Iterator<T> iterator();
/**
* Performs the given action for each element of the {@code Iterable}
* until all elements have been processed or the action throws an
* exception. Unless otherwise specified by the implementing class,
* actions are performed in the order of iteration (if an iteration order
* is specified). Exceptions thrown by the action are relayed to the
* caller.
* 为 Iterable集合实现类中的的每个元素执行给定的操作,直到处理完所有元素或操作引发异常。
* 除非实现类另有规定,否则操作按迭代顺序执行(如果指定了迭代顺序)。
* 抛出的异常被转发给调用者。
* @param action The action to be performed for each element
* action将被执行到每一个元素上
* @throws NullPointerException if the specified action is null
* @since 1.8
*/
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
/**
* Creates a {@link Spliterator} over the elements described by this
* {@code Iterable}.
* 创建一个Spliterator的实例
*
* @implSpec
* The default implementation creates an
* <em><a href="Spliterator.html#binding">early-binding</a></em>
* spliterator from the iterable's {@code Iterator}. The spliterator
* inherits the <em>fail-fast</em> properties of the iterable's iterator.
* 默认实现从迭代器的Iterator创建一个early-binding 拆分器。不懂?
* 并行迭代器继承了一般迭代器的 fail-fast属性。
* @implNote
* The default implementation should usually be overridden. The
* spliterator returned by the default implementation has poor splitting
* capabilities, is unsized, and does not report any spliterator
* characteristics. Implementing classes can nearly always provide a
* better implementation.
* 此处的默认实现通常应该被覆盖。默认实现返回的并行迭代器具有较差的并行能力、未确定大小、并且不报告任 何并行迭代器的特征。自定义的实现类几乎总能提供更好的性能。
* @return a {@code Spliterator} over the elements described by this
* {@code Iterable}.
* @since 1.8
*/
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}