openJDK的版本是openJDK8,如何下载openJDK,请参考。
这篇内容很简单。
1.List的forEach如何实现
List-1 List的forEach例子
@Testpublic void test1() { Listintegers = 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 *The default implementation behaves as if: *
{@code * for (T t : this) * action.accept(t); * }* * @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 action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); }}
看下面的图1,List接口继承了Iterable接口:
图1 List的类继承图