为什么我可以在没有 stream() 方法的 class 对象上调用 stream() 方法?

Why can I call the stream() method on objects of a class that don't have the stream()-method?

我是一名 Java 大学程序员新手。我今天发现了一些东西,打破了我关于 Java 语法如何工作的一个概念。

public class testClass {

ArrayList <String> persons = new ArrayList <String> ();

public void run(){
    Stream <String> personstream = persons.stream();
}}

ArrayList class 中找不到方法 stream(),但它可能看起来好像就在那里。当我将鼠标移到 Eclipse 中的 stream() 方法上时,它说它是 Collections 的一部分,但我在其在线文档中的任何地方都找不到 stream() 方法。

如果 stream() 方法不是我从中调用它的 class 的一部分,为什么它可以调用它?

方法 stream() 是接口 java.util.Collection 中定义的 默认 方法。查看java.util.Collection.

的来源

它使用 java.util.ArrayList 上的方法 splititerator() 来实现。

ArrayList implements the Collection界面。这个接口有方法 stream()

您是否检查了正确的 class 和 Java 版本? Java 8 的 Collection(不是 Collections)有一个 stream() default method, which is inherited by ArrayList:

/**
 * Returns a sequential {@code Stream} with this collection as its source.
 *
 * <p>This method should be overridden when the {@link #spliterator()}
 * method cannot return a spliterator that is {@code IMMUTABLE},
 * {@code CONCURRENT}, or <em>late-binding</em>. (See {@link #spliterator()}
 * for details.)
 *
 * @implSpec
 * The default implementation creates a sequential {@code Stream} from the
 * collection's {@code Spliterator}.
 *
 * @return a sequential {@code Stream} over the elements in this collection
 * @since 1.8
 */
default Stream<E> stream() {
    return StreamSupport.stream(spliterator(), false);
}

这是有效的Java8码:

List<String> persons = new ArrayList<>();
Stream<String> stream = persons.stream();

List<T>.stream() 可用。