Why the forEach method in Iterable interface is not abstract?
本问题已经有最佳答案,请猛点这里访问。
当我看到iterable接口源时,看起来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | package java.lang; import java.util.Iterator; import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; public abstract interface Iterable<T> { public abstract Iterator<T> iterator(); public void forEach(Consumer<? super T> paramConsumer) { Objects.requireNonNull(paramConsumer); Iterator localIterator = iterator(); while (localIterator.hasNext()) { Object localObject = localIterator.next(); paramConsumer.accept(localObject); } } public Spliterator<T> spliterator() { return Spliterators.spliteratorUnknownSize(iterator(), 0); } } /* Location: C:\Program Files\Java\jre1.8.0_121\lib t.jar * Qualified Name: java.lang.Iterable * Java Class Version: 8 (52.0) * JD-Core Version: 0.7.1 */ |
使用Java 8可以在接口中定义默认实现。这就是
1 2 3 4 5 6 7 8 9 10 | public interface Iterable<T> { ... default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } ... } |
您的实际代码不引用Java 8的源代码。