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

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

问题描述:

我是大学新手Java程序员。我今天发现了一些破坏了我的Java语法如何运作的概念。

I'm a novice Java programmer at university. I discovered something today that broke one of my conceptions about how Java syntax works.

public class testClass {

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

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

方法 stream()$ c在 ArrayList 类中找不到$ c>,但它可能看起来好像在那里。当我将鼠标移动到Eclipse中的 stream() -method时,它表示它是Collections的一部分,但是我找不到流( )方法在其在线文档中的任何位置。

The method stream() is not found in the ArrayList class, yet it might appear as if it's there. When I move my mouse over the stream()-method in Eclipse, it says it's part of Collections, but I don't find the stream() method anywhere in its online documentation.

如果它不是我正在调用的类的一部分,为什么调用 stream()方法呢?来自?

Why does it work to call the stream() method if it's not part of the class I'm calling it from?

您检查了正确的类和Java版本吗? Java 8的集合(不是集合)有 stream()默认方法继承ArrayList

Did you check the right class and Java version? Java 8's Collection (not Collections) has a 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);
}