openJDK的版本是openJDK8,如何下载openJDK,请参考我的这篇博客。
这篇内容很简单。
List-1 List的forEach例子
@Test
public void test1() {
List<Integer> integers = Arrays.asList(1, 4, 7, 9, 20, 3, 5, -1, -7, 10);
integers.forEach(i->{
System.out.println(i);
});
}
Arrays.asList中底层上是ArrayList,forEach的实现是在接口java.lang.Iterable中,如下List-2所示,JDK8中interface是可以有实现方法的(JDK的特性),由于该方法在Iterable中,所以直接用迭代的方式遍历整个List,之后对每个元素,调用Consumer.accept(T)方法。
List-2 Iterable的forEach方法
/**
* 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.
*
* @implSpec
* <p>The default implementation behaves as if:
* <pre>{@code
* for (T t : this)
* action.accept(t);
* }</pre>
*
* @param action The action to be performed for each element
* @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);
}
}
看下面的图1,List接口继承了Iterable接口:
图1 List的类继承图
(adsbygoogle = window.adsbygoogle || []).push({});